Make hates spaces in file names.
|
|
@ -1,651 +0,0 @@
|
|||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Joypy\n",
|
||||
"\n",
|
||||
"## Joy in Python\n",
|
||||
"\n",
|
||||
"This implementation is meant as a tool for exploring the programming model and method of Joy. Python seems like a great implementation language for Joy for several reasons.\n",
|
||||
"\n",
|
||||
"We can lean on the Python immutable types for our basic semantics and types: ints, floats, strings, and tuples, which enforces functional purity. We get garbage collection for free. Compilation via Cython. Glue language with loads of libraries."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### [Read-Eval-Print Loop (REPL)](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)\n",
|
||||
"The main way to interact with the Joy interpreter is through a simple [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) that you start by running the package:\n",
|
||||
"\n",
|
||||
" $ python -m joy\n",
|
||||
" Joypy - Copyright © 2017 Simon Forman\n",
|
||||
" This program comes with ABSOLUTELY NO WARRANTY; for details type \"warranty\".\n",
|
||||
" This is free software, and you are welcome to redistribute it\n",
|
||||
" under certain conditions; type \"sharing\" for details.\n",
|
||||
" Type \"words\" to see a list of all words, and \"[<name>] help\" to print the\n",
|
||||
" docs for a word.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" <-top\n",
|
||||
"\n",
|
||||
" joy? _\n",
|
||||
"\n",
|
||||
"The `<-top` marker points to the top of the (initially empty) stack. You can enter Joy notation at the prompt and a [trace of evaluation](#The-TracePrinter.) will be printed followed by the stack and prompt again:\n",
|
||||
"\n",
|
||||
" joy? 23 sqr 18 +\n",
|
||||
" . 23 sqr 18 +\n",
|
||||
" 23 . sqr 18 +\n",
|
||||
" 23 . dup mul 18 +\n",
|
||||
" 23 23 . mul 18 +\n",
|
||||
" 529 . 18 +\n",
|
||||
" 529 18 . +\n",
|
||||
" 547 . \n",
|
||||
"\n",
|
||||
" 547 <-top\n",
|
||||
"\n",
|
||||
" joy? \n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Stacks (aka list, quote, sequence, etc.)\n",
|
||||
"\n",
|
||||
"In Joy, in addition to the types Boolean, integer, float, and string, there is a single sequence type represented by enclosing a sequence of terms in brackets `[...]`. This sequence type is used to represent both the stack and the expression. It is a [cons list](https://en.wikipedia.org/wiki/Cons#Lists) made from Python tuples."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"§ Stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"When talking about Joy we use the terms \"stack\", \"list\", \"sequence\" and\n",
|
||||
"\"aggregate\" to mean the same thing: a simple datatype that permits\n",
|
||||
"certain operations such as iterating and pushing and popping values from\n",
|
||||
"(at least) one end.\n",
|
||||
"\n",
|
||||
"We use the venerable two-tuple recursive form of sequences where the\n",
|
||||
"empty tuple () is the empty stack and (head, rest) gives the recursive\n",
|
||||
"form of a stack with one or more items on it.\n",
|
||||
"\n",
|
||||
" ()\n",
|
||||
" (1, ())\n",
|
||||
" (2, (1, ()))\n",
|
||||
" (3, (2, (1, ())))\n",
|
||||
" ...\n",
|
||||
"\n",
|
||||
"And so on.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"We have two very simple functions to build up a stack from a Python\n",
|
||||
"iterable and also to iterate through a stack and yield its items\n",
|
||||
"one-by-one in order, and two functions to generate string representations\n",
|
||||
"of stacks:\n",
|
||||
"\n",
|
||||
" list_to_stack()\n",
|
||||
"\n",
|
||||
" iter_stack()\n",
|
||||
"\n",
|
||||
" expression_to_string() (prints left-to-right)\n",
|
||||
"\n",
|
||||
" stack_to_string() (prints right-to-left)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"A word about the stack data structure.\n",
|
||||
"\n",
|
||||
"Python has very nice \"tuple packing and unpacking\" in its syntax which\n",
|
||||
"means we can directly \"unpack\" the expected arguments to a Joy function.\n",
|
||||
"\n",
|
||||
"For example:\n",
|
||||
"\n",
|
||||
" def dup(stack):\n",
|
||||
" head, tail = stack\n",
|
||||
" return head, (head, tail)\n",
|
||||
"\n",
|
||||
"We replace the argument \"stack\" by the expected structure of the stack,\n",
|
||||
"in this case \"(head, tail)\", and Python takes care of de-structuring the\n",
|
||||
"incoming argument and assigning values to the names. Note that Python\n",
|
||||
"syntax doesn't require parentheses around tuples used in expressions\n",
|
||||
"where they would be redundant.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import inspect\n",
|
||||
"import joy.utils.stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"print inspect.getdoc(joy.utils.stack)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### The utility functions maintain order.\n",
|
||||
"The 0th item in the list will be on the top of the stack and *vise versa*."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"(1, (2, (3, ())))"
|
||||
]
|
||||
},
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"joy.utils.stack.list_to_stack([1, 2, 3])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[1, 2, 3]"
|
||||
]
|
||||
},
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"list(joy.utils.stack.iter_stack((1, (2, (3, ())))))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This requires reversing the sequence (or iterating backwards) otherwise:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"(3, (2, (1, ())))\n",
|
||||
"[3, 2, 1]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"stack = ()\n",
|
||||
"\n",
|
||||
"for n in [1, 2, 3]:\n",
|
||||
" stack = n, stack\n",
|
||||
"\n",
|
||||
"print stack\n",
|
||||
"print list(joy.utils.stack.iter_stack(stack))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Purely Functional Datastructures.\n",
|
||||
"Because Joy lists are made out of Python tuples they are immutable, so all Joy datastructures are *[purely functional](https://en.wikipedia.org/wiki/Purely_functional_data_structure)*."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# The `joy()` function.\n",
|
||||
"## An Interpreter\n",
|
||||
"The `joy()` function is extrememly simple. It accepts a stack, an expression, and a dictionary, and it iterates through the expression putting values onto the stack and delegating execution to functions it looks up in the dictionary.\n",
|
||||
"\n",
|
||||
"Each function is passed the stack, expression, and dictionary and returns them. Whatever the function returns becomes the new stack, expression, and dictionary. (The dictionary is passed to enable e.g. writing words that let you enter new words into the dictionary at runtime, which nothing does yet and may be a bad idea, and the `help` command.)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"def joy(stack, expression, dictionary, viewer=None):\n",
|
||||
" '''\n",
|
||||
" Evaluate the Joy expression on the stack.\n",
|
||||
" '''\n",
|
||||
" while expression:\n",
|
||||
"\n",
|
||||
" if viewer: viewer(stack, expression)\n",
|
||||
"\n",
|
||||
" term, expression = expression\n",
|
||||
" if isinstance(term, Symbol):\n",
|
||||
" term = dictionary[term]\n",
|
||||
" stack, expression, dictionary = term(stack, expression, dictionary)\n",
|
||||
" else:\n",
|
||||
" stack = term, stack\n",
|
||||
"\n",
|
||||
" if viewer: viewer(stack, expression)\n",
|
||||
" return stack, expression, dictionary\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import joy.joy\n",
|
||||
"\n",
|
||||
"print inspect.getsource(joy.joy.joy)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### View function\n",
|
||||
"The `joy()` function accepts a \"viewer\" function which it calls on each iteration passing the current stack and expression just before evaluation. This can be used for tracing, breakpoints, retrying after exceptions, or interrupting an evaluation and saving to disk or sending over the network to resume later. The stack and expression together contain all the state of the computation at each step."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### The `TracePrinter`.\n",
|
||||
"\n",
|
||||
"A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression (\"continuation\") on the right."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### [Continuation-Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style)\n",
|
||||
"One day I thought, What happens if you rewrite Joy to use [CSP](https://en.wikipedia.org/wiki/Continuation-passing_style)? I made all the functions accept and return the expression as well as the stack and found that all the combinators could be rewritten to work by modifying the expression rather than making recursive calls to the `joy()` function."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Parser"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"§ Converting text to a joy expression.\n",
|
||||
"\n",
|
||||
"This module exports a single function:\n",
|
||||
"\n",
|
||||
" text_to_expression(text)\n",
|
||||
"\n",
|
||||
"As well as a single Symbol class and a single Exception type:\n",
|
||||
"\n",
|
||||
" ParseError\n",
|
||||
"\n",
|
||||
"When supplied with a string this function returns a Python datastructure\n",
|
||||
"that represents the Joy datastructure described by the text expression.\n",
|
||||
"Any unbalanced square brackets will raise a ParseError.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import joy.parser\n",
|
||||
"\n",
|
||||
"print inspect.getdoc(joy.parser)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The parser is extremely simple, the undocumented `re.Scanner` class does most of the tokenizing work and then you just build the tuple structure out of the tokens. There's no Abstract Syntax Tree or anything like that."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"def _parse(tokens):\n",
|
||||
" '''\n",
|
||||
" Return a stack/list expression of the tokens.\n",
|
||||
" '''\n",
|
||||
" frame = []\n",
|
||||
" stack = []\n",
|
||||
" for tok in tokens:\n",
|
||||
" if tok == '[':\n",
|
||||
" stack.append(frame)\n",
|
||||
" frame = []\n",
|
||||
" stack[-1].append(frame)\n",
|
||||
" elif tok == ']':\n",
|
||||
" try:\n",
|
||||
" frame = stack.pop()\n",
|
||||
" except IndexError:\n",
|
||||
" raise ParseError('One or more extra closing brackets.')\n",
|
||||
" frame[-1] = list_to_stack(frame[-1])\n",
|
||||
" else:\n",
|
||||
" frame.append(tok)\n",
|
||||
" if stack:\n",
|
||||
" raise ParseError('One or more unclosed brackets.')\n",
|
||||
" return list_to_stack(frame)\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print inspect.getsource(joy.parser._parse)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"That's pretty much all there is to it."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"(1, (2, (3, (4, (5, ())))))"
|
||||
]
|
||||
},
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"joy.parser.text_to_expression('1 2 3 4 5') # A simple sequence."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"((1, (2, (3, ()))), (4, (5, ())))"
|
||||
]
|
||||
},
|
||||
"execution_count": 9,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"joy.parser.text_to_expression('[1 2 3] 4 5') # Three items, the first is a list with three items"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"(1, (23, (('four', ((-5.0, ()), (cons, ()))), (8888, ()))))"
|
||||
]
|
||||
},
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"joy.parser.text_to_expression('1 23 [\"four\" [-5.0] cons] 8888') # A mixed bag. cons is\n",
|
||||
" # a Symbol, no lookup at\n",
|
||||
" # parse-time. Haiku docs."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"((), ((), ((), ((), ((), ())))))"
|
||||
]
|
||||
},
|
||||
"execution_count": 11,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"joy.parser.text_to_expression('[][][][][]') # Five empty lists."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"((((((), ()), ()), ()), ()), ())"
|
||||
]
|
||||
},
|
||||
"execution_count": 12,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"joy.parser.text_to_expression('[[[[[]]]]]') # Five nested lists."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Library\n",
|
||||
"The Joy library of functions (aka commands, or \"words\" after Forth usage) encapsulates all the actual functionality (no pun intended) of the Joy system. There are simple functions such as addition `add` (or `+`, the library module supports aliases), and combinators which provide control-flow and higher-order operations."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 13,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"!= % & * *fraction *fraction0 + ++ - -- / < << <= <> = > >= >> ? ^ add anamorphism and app1 app2 app3 average b binary branch choice clear cleave concat cons dinfrirst dip dipd dipdd disenstacken div down_to_zero dudipd dup dupd dupdip enstacken eq first flatten floordiv gcd ge genrec getitem gt help i id ifte infra le least_fraction loop lshift lt map min mod modulus mul ne neg not nullary or over pam parse pm pop popd popdd popop pow pred primrec product quoted range range_to_zero rem remainder remove rest reverse roll< roll> rolldown rollup rshift run second select sharing shunt size sqr sqrt stack step sub succ sum swaack swap swoncat swons ternary third times truediv truthy tuck unary uncons unit unquoted unstack void warranty while words x xor zip •\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import joy.library\n",
|
||||
"\n",
|
||||
"print ' '.join(sorted(joy.library.initialize()))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Many of the functions are defined in Python, like `dip`:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 14,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"def dip(stack, expression, dictionary):\n",
|
||||
" (quote, (x, stack)) = stack\n",
|
||||
" expression = x, expression\n",
|
||||
" return stack, pushback(quote, expression), dictionary\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print inspect.getsource(joy.library.dip)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Some functions are defined in equations in terms of other functions. When the interpreter executes a definition function that function just pushes its body expression onto the pending expression (the continuation) and returns control to the interpreter."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"second == rest first\n",
|
||||
"third == rest rest first\n",
|
||||
"product == 1 swap [*] step\n",
|
||||
"swons == swap cons\n",
|
||||
"swoncat == swap concat\n",
|
||||
"flatten == [] swap [concat] step\n",
|
||||
"unit == [] cons\n",
|
||||
"quoted == [unit] dip\n",
|
||||
"unquoted == [i] dip\n",
|
||||
"enstacken == stack [clear] dip\n",
|
||||
"disenstacken == ? [uncons ?] loop pop\n",
|
||||
"? == dup truthy\n",
|
||||
"dinfrirst == dip infra first\n",
|
||||
"nullary == [stack] dinfrirst\n",
|
||||
"unary == [stack [pop] dip] dinfrirst\n",
|
||||
"binary == [stack [popop] dip] dinfrirst\n",
|
||||
"ternary == [stack [popop pop] dip] dinfrirst\n",
|
||||
"pam == [i] map\n",
|
||||
"run == [] swap infra\n",
|
||||
"sqr == dup mul\n",
|
||||
"size == 0 swap [pop ++] step\n",
|
||||
"cleave == [i] app2 [popd] dip\n",
|
||||
"average == [sum 1.0 *] [size] cleave /\n",
|
||||
"gcd == 1 [tuck modulus dup 0 >] loop pop\n",
|
||||
"least_fraction == dup [gcd] infra [div] concat map\n",
|
||||
"*fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons\n",
|
||||
"*fraction0 == concat [[swap] dip * [*] dip] infra\n",
|
||||
"down_to_zero == [0 >] [dup --] while\n",
|
||||
"range_to_zero == unit [down_to_zero] infra\n",
|
||||
"anamorphism == [pop []] swap [dip swons] genrec\n",
|
||||
"range == [0 <=] [1 - dup] anamorphism\n",
|
||||
"while == swap [nullary] cons dup dipd concat loop\n",
|
||||
"dudipd == dup dipd\n",
|
||||
"primrec == [i] genrec\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print joy.library.definitions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Currently, there's no function to add new definitions to the dictionary from \"within\" Joy code itself. Adding new definitions remains a meta-interpreter action. You have to do it yourself, in Python, and wash your hands afterward.\n",
|
||||
"\n",
|
||||
"It would be simple enough to define one, but it would open the door to *name binding* and break the idea that all state is captured in the stack and expression. There's an implicit *standard dictionary* that defines the actual semantics of the syntactic stack and expression datastructures (which only contain symbols, not the actual functions. Pickle some and see for yourself.)\n",
|
||||
"\n",
|
||||
"#### \"There should be only one.\"\n",
|
||||
"\n",
|
||||
"Which brings me to talking about one of my hopes and dreams for this notation: \"There should be only one.\" What I mean is that there should be one universal standard dictionary of commands, and all bespoke work done in a UI for purposes takes place by direct interaction and macros. There would be a *Grand Refactoring* biannually (two years, not six months, that's semi-annually) where any new definitions factored out of the usage and macros of the previous time, along with new algorithms and such, were entered into the dictionary and posted to e.g. IPFS.\n",
|
||||
"\n",
|
||||
"Code should not burgeon wildly, as it does today. The variety of code should map more-or-less to the well-factored variety of human computably-solvable problems. There shouldn't be dozens of chat apps, JS frameworks, programming languages. It's a waste of time, a [fractal \"thundering herd\" attack](https://en.wikipedia.org/wiki/Thundering_herd_problem) on human mentality.\n",
|
||||
"\n",
|
||||
"#### Literary Code Library\n",
|
||||
"\n",
|
||||
"If you read over the other notebooks you'll see that developing code in Joy is a lot like doing simple mathematics, and the descriptions of the code resemble math papers. The code also works the first time, no bugs. If you have any experience programming at all, you are probably skeptical, as I was, but it seems to work: deriving code mathematically seems to lead to fewer errors.\n",
|
||||
"\n",
|
||||
"But my point now is that this great ratio of textual explanation to wind up with code that consists of a few equations and could fit on an index card is highly desirable. Less code has fewer errors. The structure of Joy engenders a kind of thinking that seems to be very effective for developing structured processes.\n",
|
||||
"\n",
|
||||
"There seems to be an elegance and power to the notation.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
" "
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
|
|
@ -1,410 +0,0 @@
|
|||
|
||||
# Joypy
|
||||
## Joy in Python
|
||||
|
||||
This implementation is meant as a tool for exploring the programming model and method of Joy. Python seems like a great implementation language for Joy for several reasons.
|
||||
|
||||
We can lean on the Python immutable types for our basic semantics and types: ints, floats, strings, and tuples, which enforces functional purity. We get garbage collection for free. Compilation via Cython. Glue language with loads of libraries.
|
||||
|
||||
### [Read-Eval-Print Loop (REPL)](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)
|
||||
The main way to interact with the Joy interpreter is through a simple [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) that you start by running the package:
|
||||
|
||||
$ python -m joy
|
||||
Joypy - Copyright © 2017 Simon Forman
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type "warranty".
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type "sharing" for details.
|
||||
Type "words" to see a list of all words, and "[<name>] help" to print the
|
||||
docs for a word.
|
||||
|
||||
|
||||
<-top
|
||||
|
||||
joy? _
|
||||
|
||||
The `<-top` marker points to the top of the (initially empty) stack. You can enter Joy notation at the prompt and a [trace of evaluation](#The-TracePrinter.) will be printed followed by the stack and prompt again:
|
||||
|
||||
joy? 23 sqr 18 +
|
||||
. 23 sqr 18 +
|
||||
23 . sqr 18 +
|
||||
23 . dup mul 18 +
|
||||
23 23 . mul 18 +
|
||||
529 . 18 +
|
||||
529 18 . +
|
||||
547 .
|
||||
|
||||
547 <-top
|
||||
|
||||
joy?
|
||||
|
||||
|
||||
# Stacks (aka list, quote, sequence, etc.)
|
||||
|
||||
In Joy, in addition to the types Boolean, integer, float, and string, there is a single sequence type represented by enclosing a sequence of terms in brackets `[...]`. This sequence type is used to represent both the stack and the expression. It is a [cons list](https://en.wikipedia.org/wiki/Cons#Lists) made from Python tuples.
|
||||
|
||||
|
||||
```python
|
||||
import inspect
|
||||
import joy.utils.stack
|
||||
|
||||
|
||||
print inspect.getdoc(joy.utils.stack)
|
||||
```
|
||||
|
||||
§ Stack
|
||||
|
||||
|
||||
When talking about Joy we use the terms "stack", "list", "sequence" and
|
||||
"aggregate" to mean the same thing: a simple datatype that permits
|
||||
certain operations such as iterating and pushing and popping values from
|
||||
(at least) one end.
|
||||
|
||||
We use the venerable two-tuple recursive form of sequences where the
|
||||
empty tuple () is the empty stack and (head, rest) gives the recursive
|
||||
form of a stack with one or more items on it.
|
||||
|
||||
()
|
||||
(1, ())
|
||||
(2, (1, ()))
|
||||
(3, (2, (1, ())))
|
||||
...
|
||||
|
||||
And so on.
|
||||
|
||||
|
||||
We have two very simple functions to build up a stack from a Python
|
||||
iterable and also to iterate through a stack and yield its items
|
||||
one-by-one in order, and two functions to generate string representations
|
||||
of stacks:
|
||||
|
||||
list_to_stack()
|
||||
|
||||
iter_stack()
|
||||
|
||||
expression_to_string() (prints left-to-right)
|
||||
|
||||
stack_to_string() (prints right-to-left)
|
||||
|
||||
|
||||
A word about the stack data structure.
|
||||
|
||||
Python has very nice "tuple packing and unpacking" in its syntax which
|
||||
means we can directly "unpack" the expected arguments to a Joy function.
|
||||
|
||||
For example:
|
||||
|
||||
def dup(stack):
|
||||
head, tail = stack
|
||||
return head, (head, tail)
|
||||
|
||||
We replace the argument "stack" by the expected structure of the stack,
|
||||
in this case "(head, tail)", and Python takes care of de-structuring the
|
||||
incoming argument and assigning values to the names. Note that Python
|
||||
syntax doesn't require parentheses around tuples used in expressions
|
||||
where they would be redundant.
|
||||
|
||||
|
||||
### The utility functions maintain order.
|
||||
The 0th item in the list will be on the top of the stack and *vise versa*.
|
||||
|
||||
|
||||
```python
|
||||
joy.utils.stack.list_to_stack([1, 2, 3])
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
(1, (2, (3, ())))
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
list(joy.utils.stack.iter_stack((1, (2, (3, ())))))
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
[1, 2, 3]
|
||||
|
||||
|
||||
|
||||
This requires reversing the sequence (or iterating backwards) otherwise:
|
||||
|
||||
|
||||
```python
|
||||
stack = ()
|
||||
|
||||
for n in [1, 2, 3]:
|
||||
stack = n, stack
|
||||
|
||||
print stack
|
||||
print list(joy.utils.stack.iter_stack(stack))
|
||||
```
|
||||
|
||||
(3, (2, (1, ())))
|
||||
[3, 2, 1]
|
||||
|
||||
|
||||
### Purely Functional Datastructures.
|
||||
Because Joy lists are made out of Python tuples they are immutable, so all Joy datastructures are *[purely functional](https://en.wikipedia.org/wiki/Purely_functional_data_structure)*.
|
||||
|
||||
# The `joy()` function.
|
||||
## An Interpreter
|
||||
The `joy()` function is extrememly simple. It accepts a stack, an expression, and a dictionary, and it iterates through the expression putting values onto the stack and delegating execution to functions it looks up in the dictionary.
|
||||
|
||||
Each function is passed the stack, expression, and dictionary and returns them. Whatever the function returns becomes the new stack, expression, and dictionary. (The dictionary is passed to enable e.g. writing words that let you enter new words into the dictionary at runtime, which nothing does yet and may be a bad idea, and the `help` command.)
|
||||
|
||||
|
||||
```python
|
||||
import joy.joy
|
||||
|
||||
print inspect.getsource(joy.joy.joy)
|
||||
```
|
||||
|
||||
def joy(stack, expression, dictionary, viewer=None):
|
||||
'''
|
||||
Evaluate the Joy expression on the stack.
|
||||
'''
|
||||
while expression:
|
||||
|
||||
if viewer: viewer(stack, expression)
|
||||
|
||||
term, expression = expression
|
||||
if isinstance(term, Symbol):
|
||||
term = dictionary[term]
|
||||
stack, expression, dictionary = term(stack, expression, dictionary)
|
||||
else:
|
||||
stack = term, stack
|
||||
|
||||
if viewer: viewer(stack, expression)
|
||||
return stack, expression, dictionary
|
||||
|
||||
|
||||
|
||||
### View function
|
||||
The `joy()` function accepts a "viewer" function which it calls on each iteration passing the current stack and expression just before evaluation. This can be used for tracing, breakpoints, retrying after exceptions, or interrupting an evaluation and saving to disk or sending over the network to resume later. The stack and expression together contain all the state of the computation at each step.
|
||||
|
||||
### The `TracePrinter`.
|
||||
|
||||
A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression ("continuation") on the right.
|
||||
|
||||
### [Continuation-Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style)
|
||||
One day I thought, What happens if you rewrite Joy to use [CSP](https://en.wikipedia.org/wiki/Continuation-passing_style)? I made all the functions accept and return the expression as well as the stack and found that all the combinators could be rewritten to work by modifying the expression rather than making recursive calls to the `joy()` function.
|
||||
|
||||
# Parser
|
||||
|
||||
|
||||
```python
|
||||
import joy.parser
|
||||
|
||||
print inspect.getdoc(joy.parser)
|
||||
```
|
||||
|
||||
§ Converting text to a joy expression.
|
||||
|
||||
This module exports a single function:
|
||||
|
||||
text_to_expression(text)
|
||||
|
||||
As well as a single Symbol class and a single Exception type:
|
||||
|
||||
ParseError
|
||||
|
||||
When supplied with a string this function returns a Python datastructure
|
||||
that represents the Joy datastructure described by the text expression.
|
||||
Any unbalanced square brackets will raise a ParseError.
|
||||
|
||||
|
||||
The parser is extremely simple, the undocumented `re.Scanner` class does most of the tokenizing work and then you just build the tuple structure out of the tokens. There's no Abstract Syntax Tree or anything like that.
|
||||
|
||||
|
||||
```python
|
||||
print inspect.getsource(joy.parser._parse)
|
||||
```
|
||||
|
||||
def _parse(tokens):
|
||||
'''
|
||||
Return a stack/list expression of the tokens.
|
||||
'''
|
||||
frame = []
|
||||
stack = []
|
||||
for tok in tokens:
|
||||
if tok == '[':
|
||||
stack.append(frame)
|
||||
frame = []
|
||||
stack[-1].append(frame)
|
||||
elif tok == ']':
|
||||
try:
|
||||
frame = stack.pop()
|
||||
except IndexError:
|
||||
raise ParseError('One or more extra closing brackets.')
|
||||
frame[-1] = list_to_stack(frame[-1])
|
||||
else:
|
||||
frame.append(tok)
|
||||
if stack:
|
||||
raise ParseError('One or more unclosed brackets.')
|
||||
return list_to_stack(frame)
|
||||
|
||||
|
||||
|
||||
That's pretty much all there is to it.
|
||||
|
||||
|
||||
```python
|
||||
joy.parser.text_to_expression('1 2 3 4 5') # A simple sequence.
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
(1, (2, (3, (4, (5, ())))))
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
joy.parser.text_to_expression('[1 2 3] 4 5') # Three items, the first is a list with three items
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
((1, (2, (3, ()))), (4, (5, ())))
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
joy.parser.text_to_expression('1 23 ["four" [-5.0] cons] 8888') # A mixed bag. cons is
|
||||
# a Symbol, no lookup at
|
||||
# parse-time. Haiku docs.
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
(1, (23, (('four', ((-5.0, ()), (cons, ()))), (8888, ()))))
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
joy.parser.text_to_expression('[][][][][]') # Five empty lists.
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
((), ((), ((), ((), ((), ())))))
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
joy.parser.text_to_expression('[[[[[]]]]]') # Five nested lists.
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
((((((), ()), ()), ()), ()), ())
|
||||
|
||||
|
||||
|
||||
# Library
|
||||
The Joy library of functions (aka commands, or "words" after Forth usage) encapsulates all the actual functionality (no pun intended) of the Joy system. There are simple functions such as addition `add` (or `+`, the library module supports aliases), and combinators which provide control-flow and higher-order operations.
|
||||
|
||||
|
||||
```python
|
||||
import joy.library
|
||||
|
||||
print ' '.join(sorted(joy.library.initialize()))
|
||||
```
|
||||
|
||||
!= % & * *fraction *fraction0 + ++ - -- / < << <= <> = > >= >> ? ^ add anamorphism and app1 app2 app3 average b binary branch choice clear cleave concat cons dinfrirst dip dipd dipdd disenstacken div down_to_zero dudipd dup dupd dupdip enstacken eq first flatten floordiv gcd ge genrec getitem gt help i id ifte infra le least_fraction loop lshift lt map min mod modulus mul ne neg not nullary or over pam parse pm pop popd popdd popop pow pred primrec product quoted range range_to_zero rem remainder remove rest reverse roll< roll> rolldown rollup rshift run second select sharing shunt size sqr sqrt stack step sub succ sum swaack swap swoncat swons ternary third times truediv truthy tuck unary uncons unit unquoted unstack void warranty while words x xor zip •
|
||||
|
||||
|
||||
Many of the functions are defined in Python, like `dip`:
|
||||
|
||||
|
||||
```python
|
||||
print inspect.getsource(joy.library.dip)
|
||||
```
|
||||
|
||||
def dip(stack, expression, dictionary):
|
||||
(quote, (x, stack)) = stack
|
||||
expression = x, expression
|
||||
return stack, pushback(quote, expression), dictionary
|
||||
|
||||
|
||||
|
||||
Some functions are defined in equations in terms of other functions. When the interpreter executes a definition function that function just pushes its body expression onto the pending expression (the continuation) and returns control to the interpreter.
|
||||
|
||||
|
||||
```python
|
||||
print joy.library.definitions
|
||||
```
|
||||
|
||||
second == rest first
|
||||
third == rest rest first
|
||||
product == 1 swap [*] step
|
||||
swons == swap cons
|
||||
swoncat == swap concat
|
||||
flatten == [] swap [concat] step
|
||||
unit == [] cons
|
||||
quoted == [unit] dip
|
||||
unquoted == [i] dip
|
||||
enstacken == stack [clear] dip
|
||||
disenstacken == ? [uncons ?] loop pop
|
||||
? == dup truthy
|
||||
dinfrirst == dip infra first
|
||||
nullary == [stack] dinfrirst
|
||||
unary == [stack [pop] dip] dinfrirst
|
||||
binary == [stack [popop] dip] dinfrirst
|
||||
ternary == [stack [popop pop] dip] dinfrirst
|
||||
pam == [i] map
|
||||
run == [] swap infra
|
||||
sqr == dup mul
|
||||
size == 0 swap [pop ++] step
|
||||
cleave == [i] app2 [popd] dip
|
||||
average == [sum 1.0 *] [size] cleave /
|
||||
gcd == 1 [tuck modulus dup 0 >] loop pop
|
||||
least_fraction == dup [gcd] infra [div] concat map
|
||||
*fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
|
||||
*fraction0 == concat [[swap] dip * [*] dip] infra
|
||||
down_to_zero == [0 >] [dup --] while
|
||||
range_to_zero == unit [down_to_zero] infra
|
||||
anamorphism == [pop []] swap [dip swons] genrec
|
||||
range == [0 <=] [1 - dup] anamorphism
|
||||
while == swap [nullary] cons dup dipd concat loop
|
||||
dudipd == dup dipd
|
||||
primrec == [i] genrec
|
||||
|
||||
|
||||
|
||||
Currently, there's no function to add new definitions to the dictionary from "within" Joy code itself. Adding new definitions remains a meta-interpreter action. You have to do it yourself, in Python, and wash your hands afterward.
|
||||
|
||||
It would be simple enough to define one, but it would open the door to *name binding* and break the idea that all state is captured in the stack and expression. There's an implicit *standard dictionary* that defines the actual semantics of the syntactic stack and expression datastructures (which only contain symbols, not the actual functions. Pickle some and see for yourself.)
|
||||
|
||||
#### "There should be only one."
|
||||
|
||||
Which brings me to talking about one of my hopes and dreams for this notation: "There should be only one." What I mean is that there should be one universal standard dictionary of commands, and all bespoke work done in a UI for purposes takes place by direct interaction and macros. There would be a *Grand Refactoring* biannually (two years, not six months, that's semi-annually) where any new definitions factored out of the usage and macros of the previous time, along with new algorithms and such, were entered into the dictionary and posted to e.g. IPFS.
|
||||
|
||||
Code should not burgeon wildly, as it does today. The variety of code should map more-or-less to the well-factored variety of human computably-solvable problems. There shouldn't be dozens of chat apps, JS frameworks, programming languages. It's a waste of time, a [fractal "thundering herd" attack](https://en.wikipedia.org/wiki/Thundering_herd_problem) on human mentality.
|
||||
|
||||
#### Literary Code Library
|
||||
|
||||
If you read over the other notebooks you'll see that developing code in Joy is a lot like doing simple mathematics, and the descriptions of the code resemble math papers. The code also works the first time, no bugs. If you have any experience programming at all, you are probably skeptical, as I was, but it seems to work: deriving code mathematically seems to lead to fewer errors.
|
||||
|
||||
But my point now is that this great ratio of textual explanation to wind up with code that consists of a few equations and could fit on an index card is highly desirable. Less code has fewer errors. The structure of Joy engenders a kind of thinking that seems to be very effective for developing structured processes.
|
||||
|
||||
There seems to be an elegance and power to the notation.
|
||||
|
||||
|
||||
|
||||
```python
|
||||
|
||||
```
|
||||
|
|
@ -1,535 +0,0 @@
|
|||
|
||||
Joypy
|
||||
=====
|
||||
|
||||
Joy in Python
|
||||
-------------
|
||||
|
||||
This implementation is meant as a tool for exploring the programming
|
||||
model and method of Joy. Python seems like a great implementation
|
||||
language for Joy for several reasons.
|
||||
|
||||
We can lean on the Python immutable types for our basic semantics and
|
||||
types: ints, floats, strings, and tuples, which enforces functional
|
||||
purity. We get garbage collection for free. Compilation via Cython. Glue
|
||||
language with loads of libraries.
|
||||
|
||||
`Read-Eval-Print Loop (REPL) <https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop>`__
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The main way to interact with the Joy interpreter is through a simple
|
||||
`REPL <https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop>`__
|
||||
that you start by running the package:
|
||||
|
||||
::
|
||||
|
||||
$ python -m joy
|
||||
Joypy - Copyright © 2017 Simon Forman
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type "warranty".
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type "sharing" for details.
|
||||
Type "words" to see a list of all words, and "[<name>] help" to print the
|
||||
docs for a word.
|
||||
|
||||
|
||||
<-top
|
||||
|
||||
joy? _
|
||||
|
||||
The ``<-top`` marker points to the top of the (initially empty) stack.
|
||||
You can enter Joy notation at the prompt and a `trace of
|
||||
evaluation <#The-TracePrinter.>`__ will be printed followed by the stack
|
||||
and prompt again:
|
||||
|
||||
::
|
||||
|
||||
joy? 23 sqr 18 +
|
||||
. 23 sqr 18 +
|
||||
23 . sqr 18 +
|
||||
23 . dup mul 18 +
|
||||
23 23 . mul 18 +
|
||||
529 . 18 +
|
||||
529 18 . +
|
||||
547 .
|
||||
|
||||
547 <-top
|
||||
|
||||
joy?
|
||||
|
||||
Stacks (aka list, quote, sequence, etc.)
|
||||
========================================
|
||||
|
||||
In Joy, in addition to the types Boolean, integer, float, and string,
|
||||
there is a single sequence type represented by enclosing a sequence of
|
||||
terms in brackets ``[...]``. This sequence type is used to represent
|
||||
both the stack and the expression. It is a `cons
|
||||
list <https://en.wikipedia.org/wiki/Cons#Lists>`__ made from Python
|
||||
tuples.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
import inspect
|
||||
import joy.utils.stack
|
||||
|
||||
|
||||
print inspect.getdoc(joy.utils.stack)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
§ Stack
|
||||
|
||||
|
||||
When talking about Joy we use the terms "stack", "list", "sequence" and
|
||||
"aggregate" to mean the same thing: a simple datatype that permits
|
||||
certain operations such as iterating and pushing and popping values from
|
||||
(at least) one end.
|
||||
|
||||
We use the venerable two-tuple recursive form of sequences where the
|
||||
empty tuple () is the empty stack and (head, rest) gives the recursive
|
||||
form of a stack with one or more items on it.
|
||||
|
||||
()
|
||||
(1, ())
|
||||
(2, (1, ()))
|
||||
(3, (2, (1, ())))
|
||||
...
|
||||
|
||||
And so on.
|
||||
|
||||
|
||||
We have two very simple functions to build up a stack from a Python
|
||||
iterable and also to iterate through a stack and yield its items
|
||||
one-by-one in order, and two functions to generate string representations
|
||||
of stacks:
|
||||
|
||||
list_to_stack()
|
||||
|
||||
iter_stack()
|
||||
|
||||
expression_to_string() (prints left-to-right)
|
||||
|
||||
stack_to_string() (prints right-to-left)
|
||||
|
||||
|
||||
A word about the stack data structure.
|
||||
|
||||
Python has very nice "tuple packing and unpacking" in its syntax which
|
||||
means we can directly "unpack" the expected arguments to a Joy function.
|
||||
|
||||
For example:
|
||||
|
||||
def dup(stack):
|
||||
head, tail = stack
|
||||
return head, (head, tail)
|
||||
|
||||
We replace the argument "stack" by the expected structure of the stack,
|
||||
in this case "(head, tail)", and Python takes care of de-structuring the
|
||||
incoming argument and assigning values to the names. Note that Python
|
||||
syntax doesn't require parentheses around tuples used in expressions
|
||||
where they would be redundant.
|
||||
|
||||
|
||||
The utility functions maintain order.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The 0th item in the list will be on the top of the stack and *vise
|
||||
versa*.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
joy.utils.stack.list_to_stack([1, 2, 3])
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
(1, (2, (3, ())))
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
list(joy.utils.stack.iter_stack((1, (2, (3, ())))))
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[1, 2, 3]
|
||||
|
||||
|
||||
|
||||
This requires reversing the sequence (or iterating backwards) otherwise:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
stack = ()
|
||||
|
||||
for n in [1, 2, 3]:
|
||||
stack = n, stack
|
||||
|
||||
print stack
|
||||
print list(joy.utils.stack.iter_stack(stack))
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
(3, (2, (1, ())))
|
||||
[3, 2, 1]
|
||||
|
||||
|
||||
Purely Functional Datastructures.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Because Joy lists are made out of Python tuples they are immutable, so
|
||||
all Joy datastructures are *`purely
|
||||
functional <https://en.wikipedia.org/wiki/Purely_functional_data_structure>`__*.
|
||||
|
||||
The ``joy()`` function.
|
||||
=======================
|
||||
|
||||
An Interpreter
|
||||
--------------
|
||||
|
||||
The ``joy()`` function is extrememly simple. It accepts a stack, an
|
||||
expression, and a dictionary, and it iterates through the expression
|
||||
putting values onto the stack and delegating execution to functions it
|
||||
looks up in the dictionary.
|
||||
|
||||
Each function is passed the stack, expression, and dictionary and
|
||||
returns them. Whatever the function returns becomes the new stack,
|
||||
expression, and dictionary. (The dictionary is passed to enable e.g.
|
||||
writing words that let you enter new words into the dictionary at
|
||||
runtime, which nothing does yet and may be a bad idea, and the ``help``
|
||||
command.)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
import joy.joy
|
||||
|
||||
print inspect.getsource(joy.joy.joy)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
def joy(stack, expression, dictionary, viewer=None):
|
||||
'''
|
||||
Evaluate the Joy expression on the stack.
|
||||
'''
|
||||
while expression:
|
||||
|
||||
if viewer: viewer(stack, expression)
|
||||
|
||||
term, expression = expression
|
||||
if isinstance(term, Symbol):
|
||||
term = dictionary[term]
|
||||
stack, expression, dictionary = term(stack, expression, dictionary)
|
||||
else:
|
||||
stack = term, stack
|
||||
|
||||
if viewer: viewer(stack, expression)
|
||||
return stack, expression, dictionary
|
||||
|
||||
|
||||
|
||||
View function
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
The ``joy()`` function accepts a "viewer" function which it calls on
|
||||
each iteration passing the current stack and expression just before
|
||||
evaluation. This can be used for tracing, breakpoints, retrying after
|
||||
exceptions, or interrupting an evaluation and saving to disk or sending
|
||||
over the network to resume later. The stack and expression together
|
||||
contain all the state of the computation at each step.
|
||||
|
||||
The ``TracePrinter``.
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
A ``viewer`` records each step of the evaluation of a Joy program. The
|
||||
``TracePrinter`` has a facility for printing out a trace of the
|
||||
evaluation, one line per step. Each step is aligned to the current
|
||||
interpreter position, signified by a period separating the stack on the
|
||||
left from the pending expression ("continuation") on the right.
|
||||
|
||||
`Continuation-Passing Style <https://en.wikipedia.org/wiki/Continuation-passing_style>`__
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
One day I thought, What happens if you rewrite Joy to use
|
||||
`CSP <https://en.wikipedia.org/wiki/Continuation-passing_style>`__? I
|
||||
made all the functions accept and return the expression as well as the
|
||||
stack and found that all the combinators could be rewritten to work by
|
||||
modifying the expression rather than making recursive calls to the
|
||||
``joy()`` function.
|
||||
|
||||
Parser
|
||||
======
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
import joy.parser
|
||||
|
||||
print inspect.getdoc(joy.parser)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
§ Converting text to a joy expression.
|
||||
|
||||
This module exports a single function:
|
||||
|
||||
text_to_expression(text)
|
||||
|
||||
As well as a single Symbol class and a single Exception type:
|
||||
|
||||
ParseError
|
||||
|
||||
When supplied with a string this function returns a Python datastructure
|
||||
that represents the Joy datastructure described by the text expression.
|
||||
Any unbalanced square brackets will raise a ParseError.
|
||||
|
||||
|
||||
The parser is extremely simple, the undocumented ``re.Scanner`` class
|
||||
does most of the tokenizing work and then you just build the tuple
|
||||
structure out of the tokens. There's no Abstract Syntax Tree or anything
|
||||
like that.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
print inspect.getsource(joy.parser._parse)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
def _parse(tokens):
|
||||
'''
|
||||
Return a stack/list expression of the tokens.
|
||||
'''
|
||||
frame = []
|
||||
stack = []
|
||||
for tok in tokens:
|
||||
if tok == '[':
|
||||
stack.append(frame)
|
||||
frame = []
|
||||
stack[-1].append(frame)
|
||||
elif tok == ']':
|
||||
try:
|
||||
frame = stack.pop()
|
||||
except IndexError:
|
||||
raise ParseError('One or more extra closing brackets.')
|
||||
frame[-1] = list_to_stack(frame[-1])
|
||||
else:
|
||||
frame.append(tok)
|
||||
if stack:
|
||||
raise ParseError('One or more unclosed brackets.')
|
||||
return list_to_stack(frame)
|
||||
|
||||
|
||||
|
||||
That's pretty much all there is to it.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
joy.parser.text_to_expression('1 2 3 4 5') # A simple sequence.
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
(1, (2, (3, (4, (5, ())))))
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
joy.parser.text_to_expression('[1 2 3] 4 5') # Three items, the first is a list with three items
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
((1, (2, (3, ()))), (4, (5, ())))
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
joy.parser.text_to_expression('1 23 ["four" [-5.0] cons] 8888') # A mixed bag. cons is
|
||||
# a Symbol, no lookup at
|
||||
# parse-time. Haiku docs.
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
(1, (23, (('four', ((-5.0, ()), (cons, ()))), (8888, ()))))
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
joy.parser.text_to_expression('[][][][][]') # Five empty lists.
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
((), ((), ((), ((), ((), ())))))
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
joy.parser.text_to_expression('[[[[[]]]]]') # Five nested lists.
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
((((((), ()), ()), ()), ()), ())
|
||||
|
||||
|
||||
|
||||
Library
|
||||
=======
|
||||
|
||||
The Joy library of functions (aka commands, or "words" after Forth
|
||||
usage) encapsulates all the actual functionality (no pun intended) of
|
||||
the Joy system. There are simple functions such as addition ``add`` (or
|
||||
``+``, the library module supports aliases), and combinators which
|
||||
provide control-flow and higher-order operations.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
import joy.library
|
||||
|
||||
print ' '.join(sorted(joy.library.initialize()))
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
!= % & * *fraction *fraction0 + ++ - -- / < << <= <> = > >= >> ? ^ add anamorphism and app1 app2 app3 average b binary branch choice clear cleave concat cons dinfrirst dip dipd dipdd disenstacken div down_to_zero dudipd dup dupd dupdip enstacken eq first flatten floordiv gcd ge genrec getitem gt help i id ifte infra le least_fraction loop lshift lt map min mod modulus mul ne neg not nullary or over pam parse pm pop popd popdd popop pow pred primrec product quoted range range_to_zero rem remainder remove rest reverse roll< roll> rolldown rollup rshift run second select sharing shunt size sqr sqrt stack step sub succ sum swaack swap swoncat swons ternary third times truediv truthy tuck unary uncons unit unquoted unstack void warranty while words x xor zip •
|
||||
|
||||
|
||||
Many of the functions are defined in Python, like ``dip``:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
print inspect.getsource(joy.library.dip)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
def dip(stack, expression, dictionary):
|
||||
(quote, (x, stack)) = stack
|
||||
expression = x, expression
|
||||
return stack, pushback(quote, expression), dictionary
|
||||
|
||||
|
||||
|
||||
Some functions are defined in equations in terms of other functions.
|
||||
When the interpreter executes a definition function that function just
|
||||
pushes its body expression onto the pending expression (the
|
||||
continuation) and returns control to the interpreter.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
print joy.library.definitions
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
second == rest first
|
||||
third == rest rest first
|
||||
product == 1 swap [*] step
|
||||
swons == swap cons
|
||||
swoncat == swap concat
|
||||
flatten == [] swap [concat] step
|
||||
unit == [] cons
|
||||
quoted == [unit] dip
|
||||
unquoted == [i] dip
|
||||
enstacken == stack [clear] dip
|
||||
disenstacken == ? [uncons ?] loop pop
|
||||
? == dup truthy
|
||||
dinfrirst == dip infra first
|
||||
nullary == [stack] dinfrirst
|
||||
unary == [stack [pop] dip] dinfrirst
|
||||
binary == [stack [popop] dip] dinfrirst
|
||||
ternary == [stack [popop pop] dip] dinfrirst
|
||||
pam == [i] map
|
||||
run == [] swap infra
|
||||
sqr == dup mul
|
||||
size == 0 swap [pop ++] step
|
||||
cleave == [i] app2 [popd] dip
|
||||
average == [sum 1.0 *] [size] cleave /
|
||||
gcd == 1 [tuck modulus dup 0 >] loop pop
|
||||
least_fraction == dup [gcd] infra [div] concat map
|
||||
*fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
|
||||
*fraction0 == concat [[swap] dip * [*] dip] infra
|
||||
down_to_zero == [0 >] [dup --] while
|
||||
range_to_zero == unit [down_to_zero] infra
|
||||
anamorphism == [pop []] swap [dip swons] genrec
|
||||
range == [0 <=] [1 - dup] anamorphism
|
||||
while == swap [nullary] cons dup dipd concat loop
|
||||
dudipd == dup dipd
|
||||
primrec == [i] genrec
|
||||
|
||||
|
||||
|
||||
Currently, there's no function to add new definitions to the dictionary
|
||||
from "within" Joy code itself. Adding new definitions remains a
|
||||
meta-interpreter action. You have to do it yourself, in Python, and wash
|
||||
your hands afterward.
|
||||
|
||||
It would be simple enough to define one, but it would open the door to
|
||||
*name binding* and break the idea that all state is captured in the
|
||||
stack and expression. There's an implicit *standard dictionary* that
|
||||
defines the actual semantics of the syntactic stack and expression
|
||||
datastructures (which only contain symbols, not the actual functions.
|
||||
Pickle some and see for yourself.)
|
||||
|
||||
"There should be only one."
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
Which brings me to talking about one of my hopes and dreams for this
|
||||
notation: "There should be only one." What I mean is that there should
|
||||
be one universal standard dictionary of commands, and all bespoke work
|
||||
done in a UI for purposes takes place by direct interaction and macros.
|
||||
There would be a *Grand Refactoring* biannually (two years, not six
|
||||
months, that's semi-annually) where any new definitions factored out of
|
||||
the usage and macros of the previous time, along with new algorithms and
|
||||
such, were entered into the dictionary and posted to e.g. IPFS.
|
||||
|
||||
Code should not burgeon wildly, as it does today. The variety of code
|
||||
should map more-or-less to the well-factored variety of human
|
||||
computably-solvable problems. There shouldn't be dozens of chat apps, JS
|
||||
frameworks, programming languages. It's a waste of time, a `fractal
|
||||
"thundering herd"
|
||||
attack <https://en.wikipedia.org/wiki/Thundering_herd_problem>`__ on
|
||||
human mentality.
|
||||
|
||||
Literary Code Library
|
||||
^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
If you read over the other notebooks you'll see that developing code in
|
||||
Joy is a lot like doing simple mathematics, and the descriptions of the
|
||||
code resemble math papers. The code also works the first time, no bugs.
|
||||
If you have any experience programming at all, you are probably
|
||||
skeptical, as I was, but it seems to work: deriving code mathematically
|
||||
seems to lead to fewer errors.
|
||||
|
||||
But my point now is that this great ratio of textual explanation to wind
|
||||
up with code that consists of a few equations and could fit on an index
|
||||
card is highly desirable. Less code has fewer errors. The structure of
|
||||
Joy engenders a kind of thinking that seems to be very effective for
|
||||
developing structured processes.
|
||||
|
||||
There seems to be an elegance and power to the notation.
|
||||
|
||||
|
|
@ -1,240 +0,0 @@
|
|||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Preamble\n",
|
||||
"\n",
|
||||
"First, import what we need."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from joy.joy import run\n",
|
||||
"from joy.library import initialize\n",
|
||||
"from joy.utils.stack import stack_to_string\n",
|
||||
"from joy.utils.pretty_print import TracePrinter"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Define a dictionary, an initial stack, and two helper functions to run Joy code and print results for us."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"D = initialize()\n",
|
||||
"S = ()\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def J(text):\n",
|
||||
" print stack_to_string(run(text, S, D)[0])\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def V(text):\n",
|
||||
" tp = TracePrinter()\n",
|
||||
" run(text, S, D, tp.viewer)\n",
|
||||
" tp.print_()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Run some simple programs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"41\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('23 18 +')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"15\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('45 30 gcd')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### With Viewer\n",
|
||||
"\n",
|
||||
"A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression (\"continuation\") on the right. I find these traces beautiful, like a kind of art."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
" . 23 18 +\n",
|
||||
" 23 . 18 +\n",
|
||||
"23 18 . +\n",
|
||||
" 41 . \n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"V('23 18 +')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
" . 45 30 gcd\n",
|
||||
" 45 . 30 gcd\n",
|
||||
" 45 30 . gcd\n",
|
||||
" 45 30 . 1 [tuck modulus dup 0 >] loop pop\n",
|
||||
" 45 30 1 . [tuck modulus dup 0 >] loop pop\n",
|
||||
" 45 30 1 [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 45 30 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 30 45 30 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 30 15 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 30 15 15 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 30 15 15 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 30 15 True . [tuck modulus dup 0 >] loop pop\n",
|
||||
"30 15 True [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 30 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 30 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 0 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 0 0 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 0 0 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 0 False . [tuck modulus dup 0 >] loop pop\n",
|
||||
"15 0 False [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 15 0 . pop\n",
|
||||
" 15 . \n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"V('45 30 gcd')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Here's a longer trace."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
" . 96 27 gcd\n",
|
||||
" 96 . 27 gcd\n",
|
||||
" 96 27 . gcd\n",
|
||||
" 96 27 . 1 [tuck modulus dup 0 >] loop pop\n",
|
||||
" 96 27 1 . [tuck modulus dup 0 >] loop pop\n",
|
||||
" 96 27 1 [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 96 27 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 27 96 27 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 27 15 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 27 15 15 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 27 15 15 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 27 15 True . [tuck modulus dup 0 >] loop pop\n",
|
||||
"27 15 True [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 27 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 27 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 12 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 12 12 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 12 12 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 15 12 True . [tuck modulus dup 0 >] loop pop\n",
|
||||
"15 12 True [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 15 12 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 12 15 12 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 12 3 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 12 3 3 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 12 3 3 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 12 3 True . [tuck modulus dup 0 >] loop pop\n",
|
||||
" 12 3 True [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 12 3 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 3 12 3 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 3 0 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 3 0 0 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 3 0 0 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||
" 3 0 False . [tuck modulus dup 0 >] loop pop\n",
|
||||
" 3 0 False [tuck modulus dup 0 >] . loop pop\n",
|
||||
" 3 0 . pop\n",
|
||||
" 3 . \n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"V('96 27 gcd')"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
|
||||
### Preamble
|
||||
|
||||
First, import what we need.
|
||||
|
||||
|
||||
```python
|
||||
from joy.joy import run
|
||||
from joy.library import initialize
|
||||
from joy.utils.stack import stack_to_string
|
||||
from joy.utils.pretty_print import TracePrinter
|
||||
```
|
||||
|
||||
Define a dictionary, an initial stack, and two helper functions to run Joy code and print results for us.
|
||||
|
||||
|
||||
```python
|
||||
D = initialize()
|
||||
S = ()
|
||||
|
||||
|
||||
def J(text):
|
||||
print stack_to_string(run(text, S, D)[0])
|
||||
|
||||
|
||||
def V(text):
|
||||
tp = TracePrinter()
|
||||
run(text, S, D, tp.viewer)
|
||||
tp.print_()
|
||||
```
|
||||
|
||||
### Run some simple programs
|
||||
|
||||
|
||||
```python
|
||||
J('23 18 +')
|
||||
```
|
||||
|
||||
41
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('45 30 gcd')
|
||||
```
|
||||
|
||||
15
|
||||
|
||||
|
||||
### With Viewer
|
||||
|
||||
A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression ("continuation") on the right. I find these traces beautiful, like a kind of art.
|
||||
|
||||
|
||||
```python
|
||||
V('23 18 +')
|
||||
```
|
||||
|
||||
. 23 18 +
|
||||
23 . 18 +
|
||||
23 18 . +
|
||||
41 .
|
||||
|
||||
|
||||
|
||||
```python
|
||||
V('45 30 gcd')
|
||||
```
|
||||
|
||||
. 45 30 gcd
|
||||
45 . 30 gcd
|
||||
45 30 . gcd
|
||||
45 30 . 1 [tuck modulus dup 0 >] loop pop
|
||||
45 30 1 . [tuck modulus dup 0 >] loop pop
|
||||
45 30 1 [tuck modulus dup 0 >] . loop pop
|
||||
45 30 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 45 30 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 15 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 15 15 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 15 15 0 . > [tuck modulus dup 0 >] loop pop
|
||||
30 15 True . [tuck modulus dup 0 >] loop pop
|
||||
30 15 True [tuck modulus dup 0 >] . loop pop
|
||||
30 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 30 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 0 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 0 0 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 0 0 0 . > [tuck modulus dup 0 >] loop pop
|
||||
15 0 False . [tuck modulus dup 0 >] loop pop
|
||||
15 0 False [tuck modulus dup 0 >] . loop pop
|
||||
15 0 . pop
|
||||
15 .
|
||||
|
||||
|
||||
Here's a longer trace.
|
||||
|
||||
|
||||
```python
|
||||
V('96 27 gcd')
|
||||
```
|
||||
|
||||
. 96 27 gcd
|
||||
96 . 27 gcd
|
||||
96 27 . gcd
|
||||
96 27 . 1 [tuck modulus dup 0 >] loop pop
|
||||
96 27 1 . [tuck modulus dup 0 >] loop pop
|
||||
96 27 1 [tuck modulus dup 0 >] . loop pop
|
||||
96 27 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 96 27 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 15 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 15 15 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 15 15 0 . > [tuck modulus dup 0 >] loop pop
|
||||
27 15 True . [tuck modulus dup 0 >] loop pop
|
||||
27 15 True [tuck modulus dup 0 >] . loop pop
|
||||
27 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 27 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 12 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 12 12 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 12 12 0 . > [tuck modulus dup 0 >] loop pop
|
||||
15 12 True . [tuck modulus dup 0 >] loop pop
|
||||
15 12 True [tuck modulus dup 0 >] . loop pop
|
||||
15 12 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 15 12 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 3 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 3 3 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 3 3 0 . > [tuck modulus dup 0 >] loop pop
|
||||
12 3 True . [tuck modulus dup 0 >] loop pop
|
||||
12 3 True [tuck modulus dup 0 >] . loop pop
|
||||
12 3 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 12 3 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 0 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 0 0 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 0 0 0 . > [tuck modulus dup 0 >] loop pop
|
||||
3 0 False . [tuck modulus dup 0 >] loop pop
|
||||
3 0 False [tuck modulus dup 0 >] . loop pop
|
||||
3 0 . pop
|
||||
3 .
|
||||
|
||||
|
|
@ -1,154 +0,0 @@
|
|||
|
||||
Preamble
|
||||
~~~~~~~~
|
||||
|
||||
First, import what we need.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from joy.joy import run
|
||||
from joy.library import initialize
|
||||
from joy.utils.stack import stack_to_string
|
||||
from joy.utils.pretty_print import TracePrinter
|
||||
|
||||
Define a dictionary, an initial stack, and two helper functions to run
|
||||
Joy code and print results for us.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
D = initialize()
|
||||
S = ()
|
||||
|
||||
|
||||
def J(text):
|
||||
print stack_to_string(run(text, S, D)[0])
|
||||
|
||||
|
||||
def V(text):
|
||||
tp = TracePrinter()
|
||||
run(text, S, D, tp.viewer)
|
||||
tp.print_()
|
||||
|
||||
Run some simple programs
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('23 18 +')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
41
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('45 30 gcd')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
15
|
||||
|
||||
|
||||
With Viewer
|
||||
~~~~~~~~~~~
|
||||
|
||||
A ``viewer`` records each step of the evaluation of a Joy program. The
|
||||
``TracePrinter`` has a facility for printing out a trace of the
|
||||
evaluation, one line per step. Each step is aligned to the current
|
||||
interpreter position, signified by a period separating the stack on the
|
||||
left from the pending expression ("continuation") on the right. I find
|
||||
these traces beautiful, like a kind of art.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('23 18 +')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 23 18 +
|
||||
23 . 18 +
|
||||
23 18 . +
|
||||
41 .
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('45 30 gcd')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 45 30 gcd
|
||||
45 . 30 gcd
|
||||
45 30 . gcd
|
||||
45 30 . 1 [tuck modulus dup 0 >] loop pop
|
||||
45 30 1 . [tuck modulus dup 0 >] loop pop
|
||||
45 30 1 [tuck modulus dup 0 >] . loop pop
|
||||
45 30 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 45 30 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 15 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 15 15 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
30 15 15 0 . > [tuck modulus dup 0 >] loop pop
|
||||
30 15 True . [tuck modulus dup 0 >] loop pop
|
||||
30 15 True [tuck modulus dup 0 >] . loop pop
|
||||
30 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 30 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 0 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 0 0 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 0 0 0 . > [tuck modulus dup 0 >] loop pop
|
||||
15 0 False . [tuck modulus dup 0 >] loop pop
|
||||
15 0 False [tuck modulus dup 0 >] . loop pop
|
||||
15 0 . pop
|
||||
15 .
|
||||
|
||||
|
||||
Here's a longer trace.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('96 27 gcd')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 96 27 gcd
|
||||
96 . 27 gcd
|
||||
96 27 . gcd
|
||||
96 27 . 1 [tuck modulus dup 0 >] loop pop
|
||||
96 27 1 . [tuck modulus dup 0 >] loop pop
|
||||
96 27 1 [tuck modulus dup 0 >] . loop pop
|
||||
96 27 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 96 27 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 15 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 15 15 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
27 15 15 0 . > [tuck modulus dup 0 >] loop pop
|
||||
27 15 True . [tuck modulus dup 0 >] loop pop
|
||||
27 15 True [tuck modulus dup 0 >] . loop pop
|
||||
27 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 27 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 12 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 12 12 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
15 12 12 0 . > [tuck modulus dup 0 >] loop pop
|
||||
15 12 True . [tuck modulus dup 0 >] loop pop
|
||||
15 12 True [tuck modulus dup 0 >] . loop pop
|
||||
15 12 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 15 12 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 3 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 3 3 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
12 3 3 0 . > [tuck modulus dup 0 >] loop pop
|
||||
12 3 True . [tuck modulus dup 0 >] loop pop
|
||||
12 3 True [tuck modulus dup 0 >] . loop pop
|
||||
12 3 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 12 3 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 0 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 0 0 . 0 > [tuck modulus dup 0 >] loop pop
|
||||
3 0 0 0 . > [tuck modulus dup 0 >] loop pop
|
||||
3 0 False . [tuck modulus dup 0 >] loop pop
|
||||
3 0 False [tuck modulus dup 0 >] . loop pop
|
||||
3 0 . pop
|
||||
3 .
|
||||
|
||||
|
|
@ -1,694 +0,0 @@
|
|||
|
||||
# [Project Euler, first problem: "Multiples of 3 and 5"](https://projecteuler.net/problem=1)
|
||||
|
||||
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
|
||||
|
||||
Find the sum of all the multiples of 3 or 5 below 1000.
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import J, V, define
|
||||
```
|
||||
|
||||
Let's create a predicate that returns `True` if a number is a multiple of 3 or 5 and `False` otherwise.
|
||||
|
||||
|
||||
```python
|
||||
define('P == [3 % not] dupdip 5 % not or')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
V('80 P')
|
||||
```
|
||||
|
||||
. 80 P
|
||||
80 . P
|
||||
80 . [3 % not] dupdip 5 % not or
|
||||
80 [3 % not] . dupdip 5 % not or
|
||||
80 . 3 % not 80 5 % not or
|
||||
80 3 . % not 80 5 % not or
|
||||
2 . not 80 5 % not or
|
||||
False . 80 5 % not or
|
||||
False 80 . 5 % not or
|
||||
False 80 5 . % not or
|
||||
False 0 . not or
|
||||
False True . or
|
||||
True .
|
||||
|
||||
|
||||
Given the predicate function `P` a suitable program is:
|
||||
|
||||
PE1 == 1000 range [P] filter sum
|
||||
|
||||
This function generates a list of the integers from 0 to 999, filters
|
||||
that list by `P`, and then sums the result.
|
||||
|
||||
Logically this is fine, but pragmatically we are doing more work than we
|
||||
should be; we generate one thousand integers but actually use less than
|
||||
half of them. A better solution would be to generate just the multiples
|
||||
we want to sum, and to add them as we go rather than storing them and
|
||||
adding summing them at the end.
|
||||
|
||||
At first I had the idea to use two counters and increase them by three
|
||||
and five, respectively. This way we only generate the terms that we
|
||||
actually want to sum. We have to proceed by incrementing the counter
|
||||
that is lower, or if they are equal, the three counter, and we have to
|
||||
take care not to double add numbers like 15 that are multiples of both
|
||||
three and five.
|
||||
|
||||
This seemed a little clunky, so I tried a different approach.
|
||||
|
||||
Consider the first few terms in the series:
|
||||
|
||||
3 5 6 9 10 12 15 18 20 21 ...
|
||||
|
||||
Subtract each number from the one after it (subtracting 0 from 3):
|
||||
|
||||
3 5 6 9 10 12 15 18 20 21 24 25 27 30 ...
|
||||
0 3 5 6 9 10 12 15 18 20 21 24 25 27 ...
|
||||
-------------------------------------------
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 ...
|
||||
|
||||
You get this lovely repeating palindromic sequence:
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
|
||||
To make a counter that increments by factors of 3 and 5 you just add
|
||||
these differences to the counter one-by-one in a loop.
|
||||
|
||||
|
||||
To make use of this sequence to increment a counter and sum terms as we
|
||||
go we need a function that will accept the sum, the counter, and the next
|
||||
term to add, and that adds the term to the counter and a copy of the
|
||||
counter to the running sum. This function will do that:
|
||||
|
||||
PE1.1 == + [+] dupdip
|
||||
|
||||
|
||||
```python
|
||||
define('PE1.1 == + [+] dupdip')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
V('0 0 3 PE1.1')
|
||||
```
|
||||
|
||||
. 0 0 3 PE1.1
|
||||
0 . 0 3 PE1.1
|
||||
0 0 . 3 PE1.1
|
||||
0 0 3 . PE1.1
|
||||
0 0 3 . + [+] dupdip
|
||||
0 3 . [+] dupdip
|
||||
0 3 [+] . dupdip
|
||||
0 3 . + 3
|
||||
3 . 3
|
||||
3 3 .
|
||||
|
||||
|
||||
|
||||
```python
|
||||
V('0 0 [3 2 1 3 1 2 3] [PE1.1] step')
|
||||
```
|
||||
|
||||
. 0 0 [3 2 1 3 1 2 3] [PE1.1] step
|
||||
0 . 0 [3 2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 . [3 2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 [3 2 1 3 1 2 3] . [PE1.1] step
|
||||
0 0 [3 2 1 3 1 2 3] [PE1.1] . step
|
||||
0 0 3 [PE1.1] . i [2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 3 . PE1.1 [2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 3 . + [+] dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||
0 3 . [+] dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||
0 3 [+] . dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||
0 3 . + 3 [2 1 3 1 2 3] [PE1.1] step
|
||||
3 . 3 [2 1 3 1 2 3] [PE1.1] step
|
||||
3 3 . [2 1 3 1 2 3] [PE1.1] step
|
||||
3 3 [2 1 3 1 2 3] . [PE1.1] step
|
||||
3 3 [2 1 3 1 2 3] [PE1.1] . step
|
||||
3 3 2 [PE1.1] . i [1 3 1 2 3] [PE1.1] step
|
||||
3 3 2 . PE1.1 [1 3 1 2 3] [PE1.1] step
|
||||
3 3 2 . + [+] dupdip [1 3 1 2 3] [PE1.1] step
|
||||
3 5 . [+] dupdip [1 3 1 2 3] [PE1.1] step
|
||||
3 5 [+] . dupdip [1 3 1 2 3] [PE1.1] step
|
||||
3 5 . + 5 [1 3 1 2 3] [PE1.1] step
|
||||
8 . 5 [1 3 1 2 3] [PE1.1] step
|
||||
8 5 . [1 3 1 2 3] [PE1.1] step
|
||||
8 5 [1 3 1 2 3] . [PE1.1] step
|
||||
8 5 [1 3 1 2 3] [PE1.1] . step
|
||||
8 5 1 [PE1.1] . i [3 1 2 3] [PE1.1] step
|
||||
8 5 1 . PE1.1 [3 1 2 3] [PE1.1] step
|
||||
8 5 1 . + [+] dupdip [3 1 2 3] [PE1.1] step
|
||||
8 6 . [+] dupdip [3 1 2 3] [PE1.1] step
|
||||
8 6 [+] . dupdip [3 1 2 3] [PE1.1] step
|
||||
8 6 . + 6 [3 1 2 3] [PE1.1] step
|
||||
14 . 6 [3 1 2 3] [PE1.1] step
|
||||
14 6 . [3 1 2 3] [PE1.1] step
|
||||
14 6 [3 1 2 3] . [PE1.1] step
|
||||
14 6 [3 1 2 3] [PE1.1] . step
|
||||
14 6 3 [PE1.1] . i [1 2 3] [PE1.1] step
|
||||
14 6 3 . PE1.1 [1 2 3] [PE1.1] step
|
||||
14 6 3 . + [+] dupdip [1 2 3] [PE1.1] step
|
||||
14 9 . [+] dupdip [1 2 3] [PE1.1] step
|
||||
14 9 [+] . dupdip [1 2 3] [PE1.1] step
|
||||
14 9 . + 9 [1 2 3] [PE1.1] step
|
||||
23 . 9 [1 2 3] [PE1.1] step
|
||||
23 9 . [1 2 3] [PE1.1] step
|
||||
23 9 [1 2 3] . [PE1.1] step
|
||||
23 9 [1 2 3] [PE1.1] . step
|
||||
23 9 1 [PE1.1] . i [2 3] [PE1.1] step
|
||||
23 9 1 . PE1.1 [2 3] [PE1.1] step
|
||||
23 9 1 . + [+] dupdip [2 3] [PE1.1] step
|
||||
23 10 . [+] dupdip [2 3] [PE1.1] step
|
||||
23 10 [+] . dupdip [2 3] [PE1.1] step
|
||||
23 10 . + 10 [2 3] [PE1.1] step
|
||||
33 . 10 [2 3] [PE1.1] step
|
||||
33 10 . [2 3] [PE1.1] step
|
||||
33 10 [2 3] . [PE1.1] step
|
||||
33 10 [2 3] [PE1.1] . step
|
||||
33 10 2 [PE1.1] . i [3] [PE1.1] step
|
||||
33 10 2 . PE1.1 [3] [PE1.1] step
|
||||
33 10 2 . + [+] dupdip [3] [PE1.1] step
|
||||
33 12 . [+] dupdip [3] [PE1.1] step
|
||||
33 12 [+] . dupdip [3] [PE1.1] step
|
||||
33 12 . + 12 [3] [PE1.1] step
|
||||
45 . 12 [3] [PE1.1] step
|
||||
45 12 . [3] [PE1.1] step
|
||||
45 12 [3] . [PE1.1] step
|
||||
45 12 [3] [PE1.1] . step
|
||||
45 12 3 [PE1.1] . i
|
||||
45 12 3 . PE1.1
|
||||
45 12 3 . + [+] dupdip
|
||||
45 15 . [+] dupdip
|
||||
45 15 [+] . dupdip
|
||||
45 15 . + 15
|
||||
60 . 15
|
||||
60 15 .
|
||||
|
||||
|
||||
So one `step` through all seven terms brings the counter to 15 and the total to 60.
|
||||
|
||||
|
||||
```python
|
||||
1000 / 15
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
66
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
66 * 15
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
990
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
1000 - 990
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
10
|
||||
|
||||
|
||||
|
||||
We only want the terms *less than* 1000.
|
||||
|
||||
|
||||
```python
|
||||
999 - 990
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
9
|
||||
|
||||
|
||||
|
||||
That means we want to run the full list of numbers sixty-six times to get to 990 and then the first four numbers 3 2 1 3 to get to 999.
|
||||
|
||||
|
||||
```python
|
||||
define('PE1 == 0 0 66 [[3 2 1 3 1 2 3] [PE1.1] step] times [3 2 1 3] [PE1.1] step pop')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('PE1')
|
||||
```
|
||||
|
||||
233168
|
||||
|
||||
|
||||
This form uses no extra storage and produces no unused summands. It's
|
||||
good but there's one more trick we can apply. The list of seven terms
|
||||
takes up at least seven bytes. But notice that all of the terms are less
|
||||
than four, and so each can fit in just two bits. We could store all
|
||||
seven terms in just fourteen bits and use masking and shifts to pick out
|
||||
each term as we go. This will use less space and save time loading whole
|
||||
integer terms from the list.
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
0b 11 10 01 11 01 10 11 == 14811
|
||||
|
||||
|
||||
```python
|
||||
0b11100111011011
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
14811
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
define('PE1.2 == [3 & PE1.1] dupdip 2 >>')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
V('0 0 14811 PE1.2')
|
||||
```
|
||||
|
||||
. 0 0 14811 PE1.2
|
||||
0 . 0 14811 PE1.2
|
||||
0 0 . 14811 PE1.2
|
||||
0 0 14811 . PE1.2
|
||||
0 0 14811 . [3 & PE1.1] dupdip 2 >>
|
||||
0 0 14811 [3 & PE1.1] . dupdip 2 >>
|
||||
0 0 14811 . 3 & PE1.1 14811 2 >>
|
||||
0 0 14811 3 . & PE1.1 14811 2 >>
|
||||
0 0 3 . PE1.1 14811 2 >>
|
||||
0 0 3 . + [+] dupdip 14811 2 >>
|
||||
0 3 . [+] dupdip 14811 2 >>
|
||||
0 3 [+] . dupdip 14811 2 >>
|
||||
0 3 . + 3 14811 2 >>
|
||||
3 . 3 14811 2 >>
|
||||
3 3 . 14811 2 >>
|
||||
3 3 14811 . 2 >>
|
||||
3 3 14811 2 . >>
|
||||
3 3 3702 .
|
||||
|
||||
|
||||
|
||||
```python
|
||||
V('3 3 3702 PE1.2')
|
||||
```
|
||||
|
||||
. 3 3 3702 PE1.2
|
||||
3 . 3 3702 PE1.2
|
||||
3 3 . 3702 PE1.2
|
||||
3 3 3702 . PE1.2
|
||||
3 3 3702 . [3 & PE1.1] dupdip 2 >>
|
||||
3 3 3702 [3 & PE1.1] . dupdip 2 >>
|
||||
3 3 3702 . 3 & PE1.1 3702 2 >>
|
||||
3 3 3702 3 . & PE1.1 3702 2 >>
|
||||
3 3 2 . PE1.1 3702 2 >>
|
||||
3 3 2 . + [+] dupdip 3702 2 >>
|
||||
3 5 . [+] dupdip 3702 2 >>
|
||||
3 5 [+] . dupdip 3702 2 >>
|
||||
3 5 . + 5 3702 2 >>
|
||||
8 . 5 3702 2 >>
|
||||
8 5 . 3702 2 >>
|
||||
8 5 3702 . 2 >>
|
||||
8 5 3702 2 . >>
|
||||
8 5 925 .
|
||||
|
||||
|
||||
|
||||
```python
|
||||
V('0 0 14811 7 [PE1.2] times pop')
|
||||
```
|
||||
|
||||
. 0 0 14811 7 [PE1.2] times pop
|
||||
0 . 0 14811 7 [PE1.2] times pop
|
||||
0 0 . 14811 7 [PE1.2] times pop
|
||||
0 0 14811 . 7 [PE1.2] times pop
|
||||
0 0 14811 7 . [PE1.2] times pop
|
||||
0 0 14811 7 [PE1.2] . times pop
|
||||
0 0 14811 [PE1.2] . i 6 [PE1.2] times pop
|
||||
0 0 14811 . PE1.2 6 [PE1.2] times pop
|
||||
0 0 14811 . [3 & PE1.1] dupdip 2 >> 6 [PE1.2] times pop
|
||||
0 0 14811 [3 & PE1.1] . dupdip 2 >> 6 [PE1.2] times pop
|
||||
0 0 14811 . 3 & PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||
0 0 14811 3 . & PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||
0 0 3 . PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||
0 0 3 . + [+] dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||
0 3 . [+] dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||
0 3 [+] . dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||
0 3 . + 3 14811 2 >> 6 [PE1.2] times pop
|
||||
3 . 3 14811 2 >> 6 [PE1.2] times pop
|
||||
3 3 . 14811 2 >> 6 [PE1.2] times pop
|
||||
3 3 14811 . 2 >> 6 [PE1.2] times pop
|
||||
3 3 14811 2 . >> 6 [PE1.2] times pop
|
||||
3 3 3702 . 6 [PE1.2] times pop
|
||||
3 3 3702 6 . [PE1.2] times pop
|
||||
3 3 3702 6 [PE1.2] . times pop
|
||||
3 3 3702 [PE1.2] . i 5 [PE1.2] times pop
|
||||
3 3 3702 . PE1.2 5 [PE1.2] times pop
|
||||
3 3 3702 . [3 & PE1.1] dupdip 2 >> 5 [PE1.2] times pop
|
||||
3 3 3702 [3 & PE1.1] . dupdip 2 >> 5 [PE1.2] times pop
|
||||
3 3 3702 . 3 & PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||
3 3 3702 3 . & PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||
3 3 2 . PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||
3 3 2 . + [+] dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||
3 5 . [+] dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||
3 5 [+] . dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||
3 5 . + 5 3702 2 >> 5 [PE1.2] times pop
|
||||
8 . 5 3702 2 >> 5 [PE1.2] times pop
|
||||
8 5 . 3702 2 >> 5 [PE1.2] times pop
|
||||
8 5 3702 . 2 >> 5 [PE1.2] times pop
|
||||
8 5 3702 2 . >> 5 [PE1.2] times pop
|
||||
8 5 925 . 5 [PE1.2] times pop
|
||||
8 5 925 5 . [PE1.2] times pop
|
||||
8 5 925 5 [PE1.2] . times pop
|
||||
8 5 925 [PE1.2] . i 4 [PE1.2] times pop
|
||||
8 5 925 . PE1.2 4 [PE1.2] times pop
|
||||
8 5 925 . [3 & PE1.1] dupdip 2 >> 4 [PE1.2] times pop
|
||||
8 5 925 [3 & PE1.1] . dupdip 2 >> 4 [PE1.2] times pop
|
||||
8 5 925 . 3 & PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||
8 5 925 3 . & PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||
8 5 1 . PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||
8 5 1 . + [+] dupdip 925 2 >> 4 [PE1.2] times pop
|
||||
8 6 . [+] dupdip 925 2 >> 4 [PE1.2] times pop
|
||||
8 6 [+] . dupdip 925 2 >> 4 [PE1.2] times pop
|
||||
8 6 . + 6 925 2 >> 4 [PE1.2] times pop
|
||||
14 . 6 925 2 >> 4 [PE1.2] times pop
|
||||
14 6 . 925 2 >> 4 [PE1.2] times pop
|
||||
14 6 925 . 2 >> 4 [PE1.2] times pop
|
||||
14 6 925 2 . >> 4 [PE1.2] times pop
|
||||
14 6 231 . 4 [PE1.2] times pop
|
||||
14 6 231 4 . [PE1.2] times pop
|
||||
14 6 231 4 [PE1.2] . times pop
|
||||
14 6 231 [PE1.2] . i 3 [PE1.2] times pop
|
||||
14 6 231 . PE1.2 3 [PE1.2] times pop
|
||||
14 6 231 . [3 & PE1.1] dupdip 2 >> 3 [PE1.2] times pop
|
||||
14 6 231 [3 & PE1.1] . dupdip 2 >> 3 [PE1.2] times pop
|
||||
14 6 231 . 3 & PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||
14 6 231 3 . & PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||
14 6 3 . PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||
14 6 3 . + [+] dupdip 231 2 >> 3 [PE1.2] times pop
|
||||
14 9 . [+] dupdip 231 2 >> 3 [PE1.2] times pop
|
||||
14 9 [+] . dupdip 231 2 >> 3 [PE1.2] times pop
|
||||
14 9 . + 9 231 2 >> 3 [PE1.2] times pop
|
||||
23 . 9 231 2 >> 3 [PE1.2] times pop
|
||||
23 9 . 231 2 >> 3 [PE1.2] times pop
|
||||
23 9 231 . 2 >> 3 [PE1.2] times pop
|
||||
23 9 231 2 . >> 3 [PE1.2] times pop
|
||||
23 9 57 . 3 [PE1.2] times pop
|
||||
23 9 57 3 . [PE1.2] times pop
|
||||
23 9 57 3 [PE1.2] . times pop
|
||||
23 9 57 [PE1.2] . i 2 [PE1.2] times pop
|
||||
23 9 57 . PE1.2 2 [PE1.2] times pop
|
||||
23 9 57 . [3 & PE1.1] dupdip 2 >> 2 [PE1.2] times pop
|
||||
23 9 57 [3 & PE1.1] . dupdip 2 >> 2 [PE1.2] times pop
|
||||
23 9 57 . 3 & PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||
23 9 57 3 . & PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||
23 9 1 . PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||
23 9 1 . + [+] dupdip 57 2 >> 2 [PE1.2] times pop
|
||||
23 10 . [+] dupdip 57 2 >> 2 [PE1.2] times pop
|
||||
23 10 [+] . dupdip 57 2 >> 2 [PE1.2] times pop
|
||||
23 10 . + 10 57 2 >> 2 [PE1.2] times pop
|
||||
33 . 10 57 2 >> 2 [PE1.2] times pop
|
||||
33 10 . 57 2 >> 2 [PE1.2] times pop
|
||||
33 10 57 . 2 >> 2 [PE1.2] times pop
|
||||
33 10 57 2 . >> 2 [PE1.2] times pop
|
||||
33 10 14 . 2 [PE1.2] times pop
|
||||
33 10 14 2 . [PE1.2] times pop
|
||||
33 10 14 2 [PE1.2] . times pop
|
||||
33 10 14 [PE1.2] . i 1 [PE1.2] times pop
|
||||
33 10 14 . PE1.2 1 [PE1.2] times pop
|
||||
33 10 14 . [3 & PE1.1] dupdip 2 >> 1 [PE1.2] times pop
|
||||
33 10 14 [3 & PE1.1] . dupdip 2 >> 1 [PE1.2] times pop
|
||||
33 10 14 . 3 & PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||
33 10 14 3 . & PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||
33 10 2 . PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||
33 10 2 . + [+] dupdip 14 2 >> 1 [PE1.2] times pop
|
||||
33 12 . [+] dupdip 14 2 >> 1 [PE1.2] times pop
|
||||
33 12 [+] . dupdip 14 2 >> 1 [PE1.2] times pop
|
||||
33 12 . + 12 14 2 >> 1 [PE1.2] times pop
|
||||
45 . 12 14 2 >> 1 [PE1.2] times pop
|
||||
45 12 . 14 2 >> 1 [PE1.2] times pop
|
||||
45 12 14 . 2 >> 1 [PE1.2] times pop
|
||||
45 12 14 2 . >> 1 [PE1.2] times pop
|
||||
45 12 3 . 1 [PE1.2] times pop
|
||||
45 12 3 1 . [PE1.2] times pop
|
||||
45 12 3 1 [PE1.2] . times pop
|
||||
45 12 3 [PE1.2] . i pop
|
||||
45 12 3 . PE1.2 pop
|
||||
45 12 3 . [3 & PE1.1] dupdip 2 >> pop
|
||||
45 12 3 [3 & PE1.1] . dupdip 2 >> pop
|
||||
45 12 3 . 3 & PE1.1 3 2 >> pop
|
||||
45 12 3 3 . & PE1.1 3 2 >> pop
|
||||
45 12 3 . PE1.1 3 2 >> pop
|
||||
45 12 3 . + [+] dupdip 3 2 >> pop
|
||||
45 15 . [+] dupdip 3 2 >> pop
|
||||
45 15 [+] . dupdip 3 2 >> pop
|
||||
45 15 . + 15 3 2 >> pop
|
||||
60 . 15 3 2 >> pop
|
||||
60 15 . 3 2 >> pop
|
||||
60 15 3 . 2 >> pop
|
||||
60 15 3 2 . >> pop
|
||||
60 15 0 . pop
|
||||
60 15 .
|
||||
|
||||
|
||||
And so we have at last:
|
||||
|
||||
|
||||
```python
|
||||
define('PE1 == 0 0 66 [14811 7 [PE1.2] times pop] times 14811 4 [PE1.2] times popop')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('PE1')
|
||||
```
|
||||
|
||||
233168
|
||||
|
||||
|
||||
Let's refactor.
|
||||
|
||||
14811 7 [PE1.2] times pop
|
||||
14811 4 [PE1.2] times pop
|
||||
14811 n [PE1.2] times pop
|
||||
n 14811 swap [PE1.2] times pop
|
||||
|
||||
|
||||
```python
|
||||
define('PE1.3 == 14811 swap [PE1.2] times pop')
|
||||
```
|
||||
|
||||
Now we can simplify the definition above:
|
||||
|
||||
|
||||
```python
|
||||
define('PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('PE1')
|
||||
```
|
||||
|
||||
233168
|
||||
|
||||
|
||||
Here's our joy program all in one place. It doesn't make so much sense, but if you have read through the above description of how it was derived I hope it's clear.
|
||||
|
||||
PE1.1 == + [+] dupdip
|
||||
PE1.2 == [3 & PE1.1] dupdip 2 >>
|
||||
PE1.3 == 14811 swap [PE1.2] times pop
|
||||
PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
|
||||
|
||||
# Generator Version
|
||||
It's a little clunky iterating sixty-six times though the seven numbers then four more. In the _Generator Programs_ notebook we derive a generator that can be repeatedly driven by the `x` combinator to produce a stream of the seven numbers repeating over and over again.
|
||||
|
||||
|
||||
```python
|
||||
define('PE1.terms == [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('PE1.terms 21 [x] times')
|
||||
```
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]
|
||||
|
||||
|
||||
We know from above that we need sixty-six times seven then four more terms to reach up to but not over one thousand.
|
||||
|
||||
|
||||
```python
|
||||
J('7 66 * 4 +')
|
||||
```
|
||||
|
||||
466
|
||||
|
||||
|
||||
### Here they are...
|
||||
|
||||
|
||||
```python
|
||||
J('PE1.terms 466 [x] times pop')
|
||||
```
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3
|
||||
|
||||
|
||||
### ...and they do sum to 999.
|
||||
|
||||
|
||||
```python
|
||||
J('[PE1.terms 466 [x] times pop] run sum')
|
||||
```
|
||||
|
||||
999
|
||||
|
||||
|
||||
Now we can use `PE1.1` to accumulate the terms as we go, and then `pop` the generator and the counter from the stack when we're done, leaving just the sum.
|
||||
|
||||
|
||||
```python
|
||||
J('0 0 PE1.terms 466 [x [PE1.1] dip] times popop')
|
||||
```
|
||||
|
||||
233168
|
||||
|
||||
|
||||
# A little further analysis renders iteration unnecessary.
|
||||
Consider finding the sum of the positive integers less than or equal to ten.
|
||||
|
||||
|
||||
```python
|
||||
J('[10 9 8 7 6 5 4 3 2 1] sum')
|
||||
```
|
||||
|
||||
55
|
||||
|
||||
|
||||
Instead of summing them, [observe](https://en.wikipedia.org/wiki/File:Animated_proof_for_the_formula_giving_the_sum_of_the_first_integers_1%2B2%2B...%2Bn.gif):
|
||||
|
||||
10 9 8 7 6
|
||||
+ 1 2 3 4 5
|
||||
---- -- -- -- --
|
||||
11 11 11 11 11
|
||||
|
||||
11 * 5 = 55
|
||||
|
||||
From the above example we can deduce that the sum of the first N positive integers is:
|
||||
|
||||
(N + 1) * N / 2
|
||||
|
||||
(The formula also works for odd values of N, I'll leave that to you if you want to work it out or you can take my word for it.)
|
||||
|
||||
|
||||
```python
|
||||
define('F == dup ++ * 2 floordiv')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
V('10 F')
|
||||
```
|
||||
|
||||
. 10 F
|
||||
10 . F
|
||||
10 . dup ++ * 2 floordiv
|
||||
10 10 . ++ * 2 floordiv
|
||||
10 11 . * 2 floordiv
|
||||
110 . 2 floordiv
|
||||
110 2 . floordiv
|
||||
55 .
|
||||
|
||||
|
||||
## Generalizing to Blocks of Terms
|
||||
We can apply the same reasoning to the PE1 problem.
|
||||
|
||||
Between 0 and 990 inclusive there are sixty-six "blocks" of seven terms each, starting with:
|
||||
|
||||
[3 5 6 9 10 12 15]
|
||||
|
||||
And ending with:
|
||||
|
||||
[978 980 981 984 985 987 990]
|
||||
|
||||
If we reverse one of these two blocks and sum pairs...
|
||||
|
||||
|
||||
```python
|
||||
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip')
|
||||
```
|
||||
|
||||
[[978 15] [980 12] [981 10] [984 9] [985 6] [987 5] [990 3]]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map')
|
||||
```
|
||||
|
||||
[993 992 991 993 991 992 993]
|
||||
|
||||
|
||||
(Interesting that the sequence of seven numbers appears again in the rightmost digit of each term.)
|
||||
|
||||
|
||||
```python
|
||||
J('[ 3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map sum')
|
||||
```
|
||||
|
||||
6945
|
||||
|
||||
|
||||
Since there are sixty-six blocks and we are pairing them up, there must be thirty-three pairs, each of which sums to 6945. We also have these additional unpaired terms between 990 and 1000:
|
||||
|
||||
993 995 996 999
|
||||
|
||||
So we can give the "sum of all the multiples of 3 or 5 below 1000" like so:
|
||||
|
||||
|
||||
```python
|
||||
J('6945 33 * [993 995 996 999] cons sum')
|
||||
```
|
||||
|
||||
233168
|
||||
|
||||
|
||||
It's worth noting, I think, that this same reasoning holds for any two numbers $n$ and $m$ the multiples of which we hope to sum. The multiples would have a cycle of differences of length $k$ and so we could compute the sum of $Nk$ multiples as above.
|
||||
|
||||
The sequence of differences will always be a palidrome. Consider an interval spanning the least common multiple of $n$ and $m$:
|
||||
|
||||
| | | | | | | |
|
||||
| | | | |
|
||||
|
||||
Here we have 4 and 7, and you can read off the sequence of differences directly from the diagram: 4 3 1 4 2 2 4 1 3 4.
|
||||
|
||||
Geometrically, the actual values of $n$ and $m$ and their *lcm* don't matter, the pattern they make will always be symmetrical around its midpoint. The same reasoning holds for multiples of more than two numbers.
|
||||
|
||||
# The Simplest Program
|
||||
|
||||
Of course, the simplest joy program for the first Project Euler problem is just:
|
||||
|
||||
PE1 == 233168
|
||||
|
||||
Fin.
|
||||
|
|
@ -1,799 +0,0 @@
|
|||
|
||||
`Project Euler, first problem: "Multiples of 3 and 5" <https://projecteuler.net/problem=1>`__
|
||||
=============================================================================================
|
||||
|
||||
::
|
||||
|
||||
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
|
||||
|
||||
Find the sum of all the multiples of 3 or 5 below 1000.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import J, V, define
|
||||
|
||||
Let's create a predicate that returns ``True`` if a number is a multiple
|
||||
of 3 or 5 and ``False`` otherwise.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('P == [3 % not] dupdip 5 % not or')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('80 P')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 80 P
|
||||
80 . P
|
||||
80 . [3 % not] dupdip 5 % not or
|
||||
80 [3 % not] . dupdip 5 % not or
|
||||
80 . 3 % not 80 5 % not or
|
||||
80 3 . % not 80 5 % not or
|
||||
2 . not 80 5 % not or
|
||||
False . 80 5 % not or
|
||||
False 80 . 5 % not or
|
||||
False 80 5 . % not or
|
||||
False 0 . not or
|
||||
False True . or
|
||||
True .
|
||||
|
||||
|
||||
Given the predicate function ``P`` a suitable program is:
|
||||
|
||||
::
|
||||
|
||||
PE1 == 1000 range [P] filter sum
|
||||
|
||||
This function generates a list of the integers from 0 to 999, filters
|
||||
that list by ``P``, and then sums the result.
|
||||
|
||||
Logically this is fine, but pragmatically we are doing more work than we
|
||||
should be; we generate one thousand integers but actually use less than
|
||||
half of them. A better solution would be to generate just the multiples
|
||||
we want to sum, and to add them as we go rather than storing them and
|
||||
adding summing them at the end.
|
||||
|
||||
At first I had the idea to use two counters and increase them by three
|
||||
and five, respectively. This way we only generate the terms that we
|
||||
actually want to sum. We have to proceed by incrementing the counter
|
||||
that is lower, or if they are equal, the three counter, and we have to
|
||||
take care not to double add numbers like 15 that are multiples of both
|
||||
three and five.
|
||||
|
||||
This seemed a little clunky, so I tried a different approach.
|
||||
|
||||
Consider the first few terms in the series:
|
||||
|
||||
::
|
||||
|
||||
3 5 6 9 10 12 15 18 20 21 ...
|
||||
|
||||
Subtract each number from the one after it (subtracting 0 from 3):
|
||||
|
||||
::
|
||||
|
||||
3 5 6 9 10 12 15 18 20 21 24 25 27 30 ...
|
||||
0 3 5 6 9 10 12 15 18 20 21 24 25 27 ...
|
||||
-------------------------------------------
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 ...
|
||||
|
||||
You get this lovely repeating palindromic sequence:
|
||||
|
||||
::
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
|
||||
To make a counter that increments by factors of 3 and 5 you just add
|
||||
these differences to the counter one-by-one in a loop.
|
||||
|
||||
To make use of this sequence to increment a counter and sum terms as we
|
||||
go we need a function that will accept the sum, the counter, and the
|
||||
next term to add, and that adds the term to the counter and a copy of
|
||||
the counter to the running sum. This function will do that:
|
||||
|
||||
::
|
||||
|
||||
PE1.1 == + [+] dupdip
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1.1 == + [+] dupdip')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('0 0 3 PE1.1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 0 0 3 PE1.1
|
||||
0 . 0 3 PE1.1
|
||||
0 0 . 3 PE1.1
|
||||
0 0 3 . PE1.1
|
||||
0 0 3 . + [+] dupdip
|
||||
0 3 . [+] dupdip
|
||||
0 3 [+] . dupdip
|
||||
0 3 . + 3
|
||||
3 . 3
|
||||
3 3 .
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('0 0 [3 2 1 3 1 2 3] [PE1.1] step')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 0 0 [3 2 1 3 1 2 3] [PE1.1] step
|
||||
0 . 0 [3 2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 . [3 2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 [3 2 1 3 1 2 3] . [PE1.1] step
|
||||
0 0 [3 2 1 3 1 2 3] [PE1.1] . step
|
||||
0 0 3 [PE1.1] . i [2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 3 . PE1.1 [2 1 3 1 2 3] [PE1.1] step
|
||||
0 0 3 . + [+] dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||
0 3 . [+] dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||
0 3 [+] . dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||
0 3 . + 3 [2 1 3 1 2 3] [PE1.1] step
|
||||
3 . 3 [2 1 3 1 2 3] [PE1.1] step
|
||||
3 3 . [2 1 3 1 2 3] [PE1.1] step
|
||||
3 3 [2 1 3 1 2 3] . [PE1.1] step
|
||||
3 3 [2 1 3 1 2 3] [PE1.1] . step
|
||||
3 3 2 [PE1.1] . i [1 3 1 2 3] [PE1.1] step
|
||||
3 3 2 . PE1.1 [1 3 1 2 3] [PE1.1] step
|
||||
3 3 2 . + [+] dupdip [1 3 1 2 3] [PE1.1] step
|
||||
3 5 . [+] dupdip [1 3 1 2 3] [PE1.1] step
|
||||
3 5 [+] . dupdip [1 3 1 2 3] [PE1.1] step
|
||||
3 5 . + 5 [1 3 1 2 3] [PE1.1] step
|
||||
8 . 5 [1 3 1 2 3] [PE1.1] step
|
||||
8 5 . [1 3 1 2 3] [PE1.1] step
|
||||
8 5 [1 3 1 2 3] . [PE1.1] step
|
||||
8 5 [1 3 1 2 3] [PE1.1] . step
|
||||
8 5 1 [PE1.1] . i [3 1 2 3] [PE1.1] step
|
||||
8 5 1 . PE1.1 [3 1 2 3] [PE1.1] step
|
||||
8 5 1 . + [+] dupdip [3 1 2 3] [PE1.1] step
|
||||
8 6 . [+] dupdip [3 1 2 3] [PE1.1] step
|
||||
8 6 [+] . dupdip [3 1 2 3] [PE1.1] step
|
||||
8 6 . + 6 [3 1 2 3] [PE1.1] step
|
||||
14 . 6 [3 1 2 3] [PE1.1] step
|
||||
14 6 . [3 1 2 3] [PE1.1] step
|
||||
14 6 [3 1 2 3] . [PE1.1] step
|
||||
14 6 [3 1 2 3] [PE1.1] . step
|
||||
14 6 3 [PE1.1] . i [1 2 3] [PE1.1] step
|
||||
14 6 3 . PE1.1 [1 2 3] [PE1.1] step
|
||||
14 6 3 . + [+] dupdip [1 2 3] [PE1.1] step
|
||||
14 9 . [+] dupdip [1 2 3] [PE1.1] step
|
||||
14 9 [+] . dupdip [1 2 3] [PE1.1] step
|
||||
14 9 . + 9 [1 2 3] [PE1.1] step
|
||||
23 . 9 [1 2 3] [PE1.1] step
|
||||
23 9 . [1 2 3] [PE1.1] step
|
||||
23 9 [1 2 3] . [PE1.1] step
|
||||
23 9 [1 2 3] [PE1.1] . step
|
||||
23 9 1 [PE1.1] . i [2 3] [PE1.1] step
|
||||
23 9 1 . PE1.1 [2 3] [PE1.1] step
|
||||
23 9 1 . + [+] dupdip [2 3] [PE1.1] step
|
||||
23 10 . [+] dupdip [2 3] [PE1.1] step
|
||||
23 10 [+] . dupdip [2 3] [PE1.1] step
|
||||
23 10 . + 10 [2 3] [PE1.1] step
|
||||
33 . 10 [2 3] [PE1.1] step
|
||||
33 10 . [2 3] [PE1.1] step
|
||||
33 10 [2 3] . [PE1.1] step
|
||||
33 10 [2 3] [PE1.1] . step
|
||||
33 10 2 [PE1.1] . i [3] [PE1.1] step
|
||||
33 10 2 . PE1.1 [3] [PE1.1] step
|
||||
33 10 2 . + [+] dupdip [3] [PE1.1] step
|
||||
33 12 . [+] dupdip [3] [PE1.1] step
|
||||
33 12 [+] . dupdip [3] [PE1.1] step
|
||||
33 12 . + 12 [3] [PE1.1] step
|
||||
45 . 12 [3] [PE1.1] step
|
||||
45 12 . [3] [PE1.1] step
|
||||
45 12 [3] . [PE1.1] step
|
||||
45 12 [3] [PE1.1] . step
|
||||
45 12 3 [PE1.1] . i
|
||||
45 12 3 . PE1.1
|
||||
45 12 3 . + [+] dupdip
|
||||
45 15 . [+] dupdip
|
||||
45 15 [+] . dupdip
|
||||
45 15 . + 15
|
||||
60 . 15
|
||||
60 15 .
|
||||
|
||||
|
||||
So one ``step`` through all seven terms brings the counter to 15 and the
|
||||
total to 60.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
1000 / 15
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
66
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
66 * 15
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
990
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
1000 - 990
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
10
|
||||
|
||||
|
||||
|
||||
We only want the terms *less than* 1000.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
999 - 990
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
9
|
||||
|
||||
|
||||
|
||||
That means we want to run the full list of numbers sixty-six times to
|
||||
get to 990 and then the first four numbers 3 2 1 3 to get to 999.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1 == 0 0 66 [[3 2 1 3 1 2 3] [PE1.1] step] times [3 2 1 3] [PE1.1] step pop')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('PE1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
233168
|
||||
|
||||
|
||||
This form uses no extra storage and produces no unused summands. It's
|
||||
good but there's one more trick we can apply. The list of seven terms
|
||||
takes up at least seven bytes. But notice that all of the terms are less
|
||||
than four, and so each can fit in just two bits. We could store all
|
||||
seven terms in just fourteen bits and use masking and shifts to pick out
|
||||
each term as we go. This will use less space and save time loading whole
|
||||
integer terms from the list.
|
||||
|
||||
::
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
0b 11 10 01 11 01 10 11 == 14811
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
0b11100111011011
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
14811
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1.2 == [3 & PE1.1] dupdip 2 >>')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('0 0 14811 PE1.2')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 0 0 14811 PE1.2
|
||||
0 . 0 14811 PE1.2
|
||||
0 0 . 14811 PE1.2
|
||||
0 0 14811 . PE1.2
|
||||
0 0 14811 . [3 & PE1.1] dupdip 2 >>
|
||||
0 0 14811 [3 & PE1.1] . dupdip 2 >>
|
||||
0 0 14811 . 3 & PE1.1 14811 2 >>
|
||||
0 0 14811 3 . & PE1.1 14811 2 >>
|
||||
0 0 3 . PE1.1 14811 2 >>
|
||||
0 0 3 . + [+] dupdip 14811 2 >>
|
||||
0 3 . [+] dupdip 14811 2 >>
|
||||
0 3 [+] . dupdip 14811 2 >>
|
||||
0 3 . + 3 14811 2 >>
|
||||
3 . 3 14811 2 >>
|
||||
3 3 . 14811 2 >>
|
||||
3 3 14811 . 2 >>
|
||||
3 3 14811 2 . >>
|
||||
3 3 3702 .
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('3 3 3702 PE1.2')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 3 3 3702 PE1.2
|
||||
3 . 3 3702 PE1.2
|
||||
3 3 . 3702 PE1.2
|
||||
3 3 3702 . PE1.2
|
||||
3 3 3702 . [3 & PE1.1] dupdip 2 >>
|
||||
3 3 3702 [3 & PE1.1] . dupdip 2 >>
|
||||
3 3 3702 . 3 & PE1.1 3702 2 >>
|
||||
3 3 3702 3 . & PE1.1 3702 2 >>
|
||||
3 3 2 . PE1.1 3702 2 >>
|
||||
3 3 2 . + [+] dupdip 3702 2 >>
|
||||
3 5 . [+] dupdip 3702 2 >>
|
||||
3 5 [+] . dupdip 3702 2 >>
|
||||
3 5 . + 5 3702 2 >>
|
||||
8 . 5 3702 2 >>
|
||||
8 5 . 3702 2 >>
|
||||
8 5 3702 . 2 >>
|
||||
8 5 3702 2 . >>
|
||||
8 5 925 .
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('0 0 14811 7 [PE1.2] times pop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 0 0 14811 7 [PE1.2] times pop
|
||||
0 . 0 14811 7 [PE1.2] times pop
|
||||
0 0 . 14811 7 [PE1.2] times pop
|
||||
0 0 14811 . 7 [PE1.2] times pop
|
||||
0 0 14811 7 . [PE1.2] times pop
|
||||
0 0 14811 7 [PE1.2] . times pop
|
||||
0 0 14811 [PE1.2] . i 6 [PE1.2] times pop
|
||||
0 0 14811 . PE1.2 6 [PE1.2] times pop
|
||||
0 0 14811 . [3 & PE1.1] dupdip 2 >> 6 [PE1.2] times pop
|
||||
0 0 14811 [3 & PE1.1] . dupdip 2 >> 6 [PE1.2] times pop
|
||||
0 0 14811 . 3 & PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||
0 0 14811 3 . & PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||
0 0 3 . PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||
0 0 3 . + [+] dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||
0 3 . [+] dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||
0 3 [+] . dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||
0 3 . + 3 14811 2 >> 6 [PE1.2] times pop
|
||||
3 . 3 14811 2 >> 6 [PE1.2] times pop
|
||||
3 3 . 14811 2 >> 6 [PE1.2] times pop
|
||||
3 3 14811 . 2 >> 6 [PE1.2] times pop
|
||||
3 3 14811 2 . >> 6 [PE1.2] times pop
|
||||
3 3 3702 . 6 [PE1.2] times pop
|
||||
3 3 3702 6 . [PE1.2] times pop
|
||||
3 3 3702 6 [PE1.2] . times pop
|
||||
3 3 3702 [PE1.2] . i 5 [PE1.2] times pop
|
||||
3 3 3702 . PE1.2 5 [PE1.2] times pop
|
||||
3 3 3702 . [3 & PE1.1] dupdip 2 >> 5 [PE1.2] times pop
|
||||
3 3 3702 [3 & PE1.1] . dupdip 2 >> 5 [PE1.2] times pop
|
||||
3 3 3702 . 3 & PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||
3 3 3702 3 . & PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||
3 3 2 . PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||
3 3 2 . + [+] dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||
3 5 . [+] dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||
3 5 [+] . dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||
3 5 . + 5 3702 2 >> 5 [PE1.2] times pop
|
||||
8 . 5 3702 2 >> 5 [PE1.2] times pop
|
||||
8 5 . 3702 2 >> 5 [PE1.2] times pop
|
||||
8 5 3702 . 2 >> 5 [PE1.2] times pop
|
||||
8 5 3702 2 . >> 5 [PE1.2] times pop
|
||||
8 5 925 . 5 [PE1.2] times pop
|
||||
8 5 925 5 . [PE1.2] times pop
|
||||
8 5 925 5 [PE1.2] . times pop
|
||||
8 5 925 [PE1.2] . i 4 [PE1.2] times pop
|
||||
8 5 925 . PE1.2 4 [PE1.2] times pop
|
||||
8 5 925 . [3 & PE1.1] dupdip 2 >> 4 [PE1.2] times pop
|
||||
8 5 925 [3 & PE1.1] . dupdip 2 >> 4 [PE1.2] times pop
|
||||
8 5 925 . 3 & PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||
8 5 925 3 . & PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||
8 5 1 . PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||
8 5 1 . + [+] dupdip 925 2 >> 4 [PE1.2] times pop
|
||||
8 6 . [+] dupdip 925 2 >> 4 [PE1.2] times pop
|
||||
8 6 [+] . dupdip 925 2 >> 4 [PE1.2] times pop
|
||||
8 6 . + 6 925 2 >> 4 [PE1.2] times pop
|
||||
14 . 6 925 2 >> 4 [PE1.2] times pop
|
||||
14 6 . 925 2 >> 4 [PE1.2] times pop
|
||||
14 6 925 . 2 >> 4 [PE1.2] times pop
|
||||
14 6 925 2 . >> 4 [PE1.2] times pop
|
||||
14 6 231 . 4 [PE1.2] times pop
|
||||
14 6 231 4 . [PE1.2] times pop
|
||||
14 6 231 4 [PE1.2] . times pop
|
||||
14 6 231 [PE1.2] . i 3 [PE1.2] times pop
|
||||
14 6 231 . PE1.2 3 [PE1.2] times pop
|
||||
14 6 231 . [3 & PE1.1] dupdip 2 >> 3 [PE1.2] times pop
|
||||
14 6 231 [3 & PE1.1] . dupdip 2 >> 3 [PE1.2] times pop
|
||||
14 6 231 . 3 & PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||
14 6 231 3 . & PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||
14 6 3 . PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||
14 6 3 . + [+] dupdip 231 2 >> 3 [PE1.2] times pop
|
||||
14 9 . [+] dupdip 231 2 >> 3 [PE1.2] times pop
|
||||
14 9 [+] . dupdip 231 2 >> 3 [PE1.2] times pop
|
||||
14 9 . + 9 231 2 >> 3 [PE1.2] times pop
|
||||
23 . 9 231 2 >> 3 [PE1.2] times pop
|
||||
23 9 . 231 2 >> 3 [PE1.2] times pop
|
||||
23 9 231 . 2 >> 3 [PE1.2] times pop
|
||||
23 9 231 2 . >> 3 [PE1.2] times pop
|
||||
23 9 57 . 3 [PE1.2] times pop
|
||||
23 9 57 3 . [PE1.2] times pop
|
||||
23 9 57 3 [PE1.2] . times pop
|
||||
23 9 57 [PE1.2] . i 2 [PE1.2] times pop
|
||||
23 9 57 . PE1.2 2 [PE1.2] times pop
|
||||
23 9 57 . [3 & PE1.1] dupdip 2 >> 2 [PE1.2] times pop
|
||||
23 9 57 [3 & PE1.1] . dupdip 2 >> 2 [PE1.2] times pop
|
||||
23 9 57 . 3 & PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||
23 9 57 3 . & PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||
23 9 1 . PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||
23 9 1 . + [+] dupdip 57 2 >> 2 [PE1.2] times pop
|
||||
23 10 . [+] dupdip 57 2 >> 2 [PE1.2] times pop
|
||||
23 10 [+] . dupdip 57 2 >> 2 [PE1.2] times pop
|
||||
23 10 . + 10 57 2 >> 2 [PE1.2] times pop
|
||||
33 . 10 57 2 >> 2 [PE1.2] times pop
|
||||
33 10 . 57 2 >> 2 [PE1.2] times pop
|
||||
33 10 57 . 2 >> 2 [PE1.2] times pop
|
||||
33 10 57 2 . >> 2 [PE1.2] times pop
|
||||
33 10 14 . 2 [PE1.2] times pop
|
||||
33 10 14 2 . [PE1.2] times pop
|
||||
33 10 14 2 [PE1.2] . times pop
|
||||
33 10 14 [PE1.2] . i 1 [PE1.2] times pop
|
||||
33 10 14 . PE1.2 1 [PE1.2] times pop
|
||||
33 10 14 . [3 & PE1.1] dupdip 2 >> 1 [PE1.2] times pop
|
||||
33 10 14 [3 & PE1.1] . dupdip 2 >> 1 [PE1.2] times pop
|
||||
33 10 14 . 3 & PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||
33 10 14 3 . & PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||
33 10 2 . PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||
33 10 2 . + [+] dupdip 14 2 >> 1 [PE1.2] times pop
|
||||
33 12 . [+] dupdip 14 2 >> 1 [PE1.2] times pop
|
||||
33 12 [+] . dupdip 14 2 >> 1 [PE1.2] times pop
|
||||
33 12 . + 12 14 2 >> 1 [PE1.2] times pop
|
||||
45 . 12 14 2 >> 1 [PE1.2] times pop
|
||||
45 12 . 14 2 >> 1 [PE1.2] times pop
|
||||
45 12 14 . 2 >> 1 [PE1.2] times pop
|
||||
45 12 14 2 . >> 1 [PE1.2] times pop
|
||||
45 12 3 . 1 [PE1.2] times pop
|
||||
45 12 3 1 . [PE1.2] times pop
|
||||
45 12 3 1 [PE1.2] . times pop
|
||||
45 12 3 [PE1.2] . i pop
|
||||
45 12 3 . PE1.2 pop
|
||||
45 12 3 . [3 & PE1.1] dupdip 2 >> pop
|
||||
45 12 3 [3 & PE1.1] . dupdip 2 >> pop
|
||||
45 12 3 . 3 & PE1.1 3 2 >> pop
|
||||
45 12 3 3 . & PE1.1 3 2 >> pop
|
||||
45 12 3 . PE1.1 3 2 >> pop
|
||||
45 12 3 . + [+] dupdip 3 2 >> pop
|
||||
45 15 . [+] dupdip 3 2 >> pop
|
||||
45 15 [+] . dupdip 3 2 >> pop
|
||||
45 15 . + 15 3 2 >> pop
|
||||
60 . 15 3 2 >> pop
|
||||
60 15 . 3 2 >> pop
|
||||
60 15 3 . 2 >> pop
|
||||
60 15 3 2 . >> pop
|
||||
60 15 0 . pop
|
||||
60 15 .
|
||||
|
||||
|
||||
And so we have at last:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1 == 0 0 66 [14811 7 [PE1.2] times pop] times 14811 4 [PE1.2] times popop')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('PE1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
233168
|
||||
|
||||
|
||||
Let's refactor.
|
||||
|
||||
::
|
||||
|
||||
14811 7 [PE1.2] times pop
|
||||
14811 4 [PE1.2] times pop
|
||||
14811 n [PE1.2] times pop
|
||||
n 14811 swap [PE1.2] times pop
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1.3 == 14811 swap [PE1.2] times pop')
|
||||
|
||||
Now we can simplify the definition above:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('PE1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
233168
|
||||
|
||||
|
||||
Here's our joy program all in one place. It doesn't make so much sense,
|
||||
but if you have read through the above description of how it was derived
|
||||
I hope it's clear.
|
||||
|
||||
::
|
||||
|
||||
PE1.1 == + [+] dupdip
|
||||
PE1.2 == [3 & PE1.1] dupdip 2 >>
|
||||
PE1.3 == 14811 swap [PE1.2] times pop
|
||||
PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
|
||||
|
||||
Generator Version
|
||||
=================
|
||||
|
||||
It's a little clunky iterating sixty-six times though the seven numbers
|
||||
then four more. In the *Generator Programs* notebook we derive a
|
||||
generator that can be repeatedly driven by the ``x`` combinator to
|
||||
produce a stream of the seven numbers repeating over and over again.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1.terms == [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('PE1.terms 21 [x] times')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]
|
||||
|
||||
|
||||
We know from above that we need sixty-six times seven then four more
|
||||
terms to reach up to but not over one thousand.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('7 66 * 4 +')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
466
|
||||
|
||||
|
||||
Here they are...
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('PE1.terms 466 [x] times pop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3
|
||||
|
||||
|
||||
...and they do sum to 999.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[PE1.terms 466 [x] times pop] run sum')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
999
|
||||
|
||||
|
||||
Now we can use ``PE1.1`` to accumulate the terms as we go, and then
|
||||
``pop`` the generator and the counter from the stack when we're done,
|
||||
leaving just the sum.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('0 0 PE1.terms 466 [x [PE1.1] dip] times popop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
233168
|
||||
|
||||
|
||||
A little further analysis renders iteration unnecessary.
|
||||
========================================================
|
||||
|
||||
Consider finding the sum of the positive integers less than or equal to
|
||||
ten.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[10 9 8 7 6 5 4 3 2 1] sum')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
55
|
||||
|
||||
|
||||
Instead of summing them,
|
||||
`observe <https://en.wikipedia.org/wiki/File:Animated_proof_for_the_formula_giving_the_sum_of_the_first_integers_1%2B2%2B...%2Bn.gif>`__:
|
||||
|
||||
::
|
||||
|
||||
10 9 8 7 6
|
||||
+ 1 2 3 4 5
|
||||
---- -- -- -- --
|
||||
11 11 11 11 11
|
||||
|
||||
11 * 5 = 55
|
||||
|
||||
From the above example we can deduce that the sum of the first N
|
||||
positive integers is:
|
||||
|
||||
::
|
||||
|
||||
(N + 1) * N / 2
|
||||
|
||||
(The formula also works for odd values of N, I'll leave that to you if
|
||||
you want to work it out or you can take my word for it.)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('F == dup ++ * 2 floordiv')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('10 F')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 10 F
|
||||
10 . F
|
||||
10 . dup ++ * 2 floordiv
|
||||
10 10 . ++ * 2 floordiv
|
||||
10 11 . * 2 floordiv
|
||||
110 . 2 floordiv
|
||||
110 2 . floordiv
|
||||
55 .
|
||||
|
||||
|
||||
Generalizing to Blocks of Terms
|
||||
-------------------------------
|
||||
|
||||
We can apply the same reasoning to the PE1 problem.
|
||||
|
||||
Between 0 and 990 inclusive there are sixty-six "blocks" of seven terms
|
||||
each, starting with:
|
||||
|
||||
::
|
||||
|
||||
[3 5 6 9 10 12 15]
|
||||
|
||||
And ending with:
|
||||
|
||||
::
|
||||
|
||||
[978 980 981 984 985 987 990]
|
||||
|
||||
If we reverse one of these two blocks and sum pairs...
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[[978 15] [980 12] [981 10] [984 9] [985 6] [987 5] [990 3]]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[993 992 991 993 991 992 993]
|
||||
|
||||
|
||||
(Interesting that the sequence of seven numbers appears again in the
|
||||
rightmost digit of each term.)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[ 3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map sum')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
6945
|
||||
|
||||
|
||||
Since there are sixty-six blocks and we are pairing them up, there must
|
||||
be thirty-three pairs, each of which sums to 6945. We also have these
|
||||
additional unpaired terms between 990 and 1000:
|
||||
|
||||
::
|
||||
|
||||
993 995 996 999
|
||||
|
||||
So we can give the "sum of all the multiples of 3 or 5 below 1000" like
|
||||
so:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('6945 33 * [993 995 996 999] cons sum')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
233168
|
||||
|
||||
|
||||
It's worth noting, I think, that this same reasoning holds for any two
|
||||
numbers :math:`n` and :math:`m` the multiples of which we hope to sum.
|
||||
The multiples would have a cycle of differences of length :math:`k` and
|
||||
so we could compute the sum of :math:`Nk` multiples as above.
|
||||
|
||||
The sequence of differences will always be a palidrome. Consider an
|
||||
interval spanning the least common multiple of :math:`n` and :math:`m`:
|
||||
|
||||
::
|
||||
|
||||
| | | | | | | |
|
||||
| | | | |
|
||||
|
||||
Here we have 4 and 7, and you can read off the sequence of differences
|
||||
directly from the diagram: 4 3 1 4 2 2 4 1 3 4.
|
||||
|
||||
Geometrically, the actual values of :math:`n` and :math:`m` and their
|
||||
*lcm* don't matter, the pattern they make will always be symmetrical
|
||||
around its midpoint. The same reasoning holds for multiples of more than
|
||||
two numbers.
|
||||
|
||||
The Simplest Program
|
||||
====================
|
||||
|
||||
Of course, the simplest joy program for the first Project Euler problem
|
||||
is just:
|
||||
|
||||
::
|
||||
|
||||
PE1 == 233168
|
||||
|
||||
Fin.
|
||||
|
|
@ -1,455 +0,0 @@
|
|||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Advent of Code 2017\n",
|
||||
"\n",
|
||||
"## December 1st\n",
|
||||
"\n",
|
||||
"\\[Given\\] a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.\n",
|
||||
"\n",
|
||||
"For example:\n",
|
||||
"\n",
|
||||
"* 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.\n",
|
||||
"* 1111 produces 4 because each digit (all 1) matches the next.\n",
|
||||
"* 1234 produces 0 because no digit matches the next.\n",
|
||||
"* 91212129 produces 9 because the only digit that matches the next one is the last digit, 9."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from notebook_preamble import J, V, define"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"I'll assume the input is a Joy sequence of integers (as opposed to a string or something else.)\n",
|
||||
"\n",
|
||||
"We might proceed by creating a word that makes a copy of the sequence with the first item moved to the last, and zips it with the original to make a list of pairs, and a another word that adds (one of) each pair to a total if the pair matches.\n",
|
||||
"\n",
|
||||
" AoC2017.1 == pair_up total_matches\n",
|
||||
"\n",
|
||||
"Let's derive `pair_up`:\n",
|
||||
"\n",
|
||||
" [a b c] pair_up\n",
|
||||
" -------------------------\n",
|
||||
" [[a b] [b c] [c a]]\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Straightforward (although the order of each pair is reversed, due to the way `zip` works, but it doesn't matter for this program):\n",
|
||||
"\n",
|
||||
" [a b c] dup\n",
|
||||
" [a b c] [a b c] uncons swap\n",
|
||||
" [a b c] [b c] a unit concat\n",
|
||||
" [a b c] [b c a] zip\n",
|
||||
" [[b a] [c b] [a c]]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('pair_up == dup uncons swap unit concat zip')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[[2 1] [3 2] [1 3]]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 3] pair_up')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[[2 1] [2 2] [3 2] [1 3]]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 2 3] pair_up')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we need to derive `total_matches`. It will be a `step` function:\n",
|
||||
"\n",
|
||||
" total_matches == 0 swap [F] step\n",
|
||||
"\n",
|
||||
"Where `F` will have the pair to work with, and it will basically be a `branch` or `ifte`.\n",
|
||||
"\n",
|
||||
" total [n m] F\n",
|
||||
"\n",
|
||||
"It will probably be easier to write if we dequote the pair:\n",
|
||||
"\n",
|
||||
" total [n m] i F′\n",
|
||||
" ----------------------\n",
|
||||
" total n m F′\n",
|
||||
"\n",
|
||||
"Now `F′` becomes just:\n",
|
||||
"\n",
|
||||
" total n m [=] [pop +] [popop] ifte\n",
|
||||
"\n",
|
||||
"So:\n",
|
||||
"\n",
|
||||
" F == i [=] [pop +] [popop] ifte\n",
|
||||
"\n",
|
||||
"And thus:\n",
|
||||
"\n",
|
||||
" total_matches == 0 swap [i [=] [pop +] [popop] ifte] step"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('total_matches == 0 swap [i [=] [pop +] [popop] ifte] step')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"0\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 3] pair_up total_matches')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"2\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 2 3] pair_up total_matches')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we can define our main program and evaluate it on the examples."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('AoC2017.1 == pair_up total_matches')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"3\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 1 2 2] AoC2017.1')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"4\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 1 1 1] AoC2017.1')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"0\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 3 4] AoC2017.1')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"9\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[9 1 2 1 2 1 2 9] AoC2017.1')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 13,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"9\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[9 1 2 1 2 1 2 9] AoC2017.1')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
" pair_up == dup uncons swap unit concat zip\n",
|
||||
" total_matches == 0 swap [i [=] [pop +] [popop] ifte] step\n",
|
||||
"\n",
|
||||
" AoC2017.1 == pair_up total_matches"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now the paired digit is \"halfway\" round.\n",
|
||||
"\n",
|
||||
" [a b c d] dup size 2 / [drop] [take reverse] cleave concat zip"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 14,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[[3 1] [4 2] [1 3] [2 4]]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave concat zip')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"I realized that each pair is repeated..."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[1 2 3 4] [[1 3] [2 4]]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave zip')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 16,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('AoC2017.1.extra == dup size 2 / [drop] [take reverse] cleave zip swap pop total_matches 2 *')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 17,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"6\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 1 2] AoC2017.1.extra')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 18,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"0\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 2 1] AoC2017.1.extra')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"4\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 3 4 2 5] AoC2017.1.extra')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Refactor FTW\n",
|
||||
"\n",
|
||||
"With Joy a great deal of the heuristics from Forth programming carry over nicely. For example, refactoring into small, well-scoped commands with mnemonic names...\n",
|
||||
"\n",
|
||||
" rotate_seq == uncons swap unit concat\n",
|
||||
" pair_up == dup rotate_seq zip\n",
|
||||
" add_if_match == [=] [pop +] [popop] ifte\n",
|
||||
" total_matches == [i add_if_match] step_zero\n",
|
||||
"\n",
|
||||
" AoC2017.1 == pair_up total_matches\n",
|
||||
"\n",
|
||||
" half_of_size == dup size 2 /\n",
|
||||
" split_at == [drop] [take reverse] cleave\n",
|
||||
" pair_up.extra == half_of_size split_at zip swap pop\n",
|
||||
"\n",
|
||||
" AoC2017.1.extra == pair_up.extra total_matches 2 *\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
|
|
@ -1,228 +0,0 @@
|
|||
|
||||
# Advent of Code 2017
|
||||
|
||||
## December 1st
|
||||
|
||||
\[Given\] a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.
|
||||
|
||||
For example:
|
||||
|
||||
* 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
|
||||
* 1111 produces 4 because each digit (all 1) matches the next.
|
||||
* 1234 produces 0 because no digit matches the next.
|
||||
* 91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import J, V, define
|
||||
```
|
||||
|
||||
I'll assume the input is a Joy sequence of integers (as opposed to a string or something else.)
|
||||
|
||||
We might proceed by creating a word that makes a copy of the sequence with the first item moved to the last, and zips it with the original to make a list of pairs, and a another word that adds (one of) each pair to a total if the pair matches.
|
||||
|
||||
AoC2017.1 == pair_up total_matches
|
||||
|
||||
Let's derive `pair_up`:
|
||||
|
||||
[a b c] pair_up
|
||||
-------------------------
|
||||
[[a b] [b c] [c a]]
|
||||
|
||||
|
||||
Straightforward (although the order of each pair is reversed, due to the way `zip` works, but it doesn't matter for this program):
|
||||
|
||||
[a b c] dup
|
||||
[a b c] [a b c] uncons swap
|
||||
[a b c] [b c] a unit concat
|
||||
[a b c] [b c a] zip
|
||||
[[b a] [c b] [a c]]
|
||||
|
||||
|
||||
```python
|
||||
define('pair_up == dup uncons swap unit concat zip')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 3] pair_up')
|
||||
```
|
||||
|
||||
[[2 1] [3 2] [1 3]]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 2 3] pair_up')
|
||||
```
|
||||
|
||||
[[2 1] [2 2] [3 2] [1 3]]
|
||||
|
||||
|
||||
Now we need to derive `total_matches`. It will be a `step` function:
|
||||
|
||||
total_matches == 0 swap [F] step
|
||||
|
||||
Where `F` will have the pair to work with, and it will basically be a `branch` or `ifte`.
|
||||
|
||||
total [n m] F
|
||||
|
||||
It will probably be easier to write if we dequote the pair:
|
||||
|
||||
total [n m] i F′
|
||||
----------------------
|
||||
total n m F′
|
||||
|
||||
Now `F′` becomes just:
|
||||
|
||||
total n m [=] [pop +] [popop] ifte
|
||||
|
||||
So:
|
||||
|
||||
F == i [=] [pop +] [popop] ifte
|
||||
|
||||
And thus:
|
||||
|
||||
total_matches == 0 swap [i [=] [pop +] [popop] ifte] step
|
||||
|
||||
|
||||
```python
|
||||
define('total_matches == 0 swap [i [=] [pop +] [popop] ifte] step')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 3] pair_up total_matches')
|
||||
```
|
||||
|
||||
0
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 2 3] pair_up total_matches')
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
|
||||
Now we can define our main program and evaluate it on the examples.
|
||||
|
||||
|
||||
```python
|
||||
define('AoC2017.1 == pair_up total_matches')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[1 1 2 2] AoC2017.1')
|
||||
```
|
||||
|
||||
3
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 1 1 1] AoC2017.1')
|
||||
```
|
||||
|
||||
4
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 3 4] AoC2017.1')
|
||||
```
|
||||
|
||||
0
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[9 1 2 1 2 1 2 9] AoC2017.1')
|
||||
```
|
||||
|
||||
9
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[9 1 2 1 2 1 2 9] AoC2017.1')
|
||||
```
|
||||
|
||||
9
|
||||
|
||||
|
||||
pair_up == dup uncons swap unit concat zip
|
||||
total_matches == 0 swap [i [=] [pop +] [popop] ifte] step
|
||||
|
||||
AoC2017.1 == pair_up total_matches
|
||||
|
||||
Now the paired digit is "halfway" round.
|
||||
|
||||
[a b c d] dup size 2 / [drop] [take reverse] cleave concat zip
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave concat zip')
|
||||
```
|
||||
|
||||
[[3 1] [4 2] [1 3] [2 4]]
|
||||
|
||||
|
||||
I realized that each pair is repeated...
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave zip')
|
||||
```
|
||||
|
||||
[1 2 3 4] [[1 3] [2 4]]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
define('AoC2017.1.extra == dup size 2 / [drop] [take reverse] cleave zip swap pop total_matches 2 *')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 1 2] AoC2017.1.extra')
|
||||
```
|
||||
|
||||
6
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 2 1] AoC2017.1.extra')
|
||||
```
|
||||
|
||||
0
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 3 4 2 5] AoC2017.1.extra')
|
||||
```
|
||||
|
||||
4
|
||||
|
||||
|
||||
# Refactor FTW
|
||||
|
||||
With Joy a great deal of the heuristics from Forth programming carry over nicely. For example, refactoring into small, well-scoped commands with mnemonic names...
|
||||
|
||||
rotate_seq == uncons swap unit concat
|
||||
pair_up == dup rotate_seq zip
|
||||
add_if_match == [=] [pop +] [popop] ifte
|
||||
total_matches == [i add_if_match] step_zero
|
||||
|
||||
AoC2017.1 == pair_up total_matches
|
||||
|
||||
half_of_size == dup size 2 /
|
||||
split_at == [drop] [take reverse] cleave
|
||||
pair_up.extra == half_of_size split_at zip swap pop
|
||||
|
||||
AoC2017.1.extra == pair_up.extra total_matches 2 *
|
||||
|
||||
|
|
@ -1,288 +0,0 @@
|
|||
|
||||
Advent of Code 2017
|
||||
===================
|
||||
|
||||
December 1st
|
||||
------------
|
||||
|
||||
[Given] a sequence of digits (your puzzle input) and find the sum of all
|
||||
digits that match the next digit in the list. The list is circular, so
|
||||
the digit after the last digit is the first digit in the list.
|
||||
|
||||
For example:
|
||||
|
||||
- 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches
|
||||
the second digit and the third digit (2) matches the fourth digit.
|
||||
- 1111 produces 4 because each digit (all 1) matches the next.
|
||||
- 1234 produces 0 because no digit matches the next.
|
||||
- 91212129 produces 9 because the only digit that matches the next one
|
||||
is the last digit, 9.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import J, V, define
|
||||
|
||||
I'll assume the input is a Joy sequence of integers (as opposed to a
|
||||
string or something else.)
|
||||
|
||||
We might proceed by creating a word that makes a copy of the sequence
|
||||
with the first item moved to the last, and zips it with the original to
|
||||
make a list of pairs, and a another word that adds (one of) each pair to
|
||||
a total if the pair matches.
|
||||
|
||||
::
|
||||
|
||||
AoC2017.1 == pair_up total_matches
|
||||
|
||||
Let's derive ``pair_up``:
|
||||
|
||||
::
|
||||
|
||||
[a b c] pair_up
|
||||
-------------------------
|
||||
[[a b] [b c] [c a]]
|
||||
|
||||
Straightforward (although the order of each pair is reversed, due to the
|
||||
way ``zip`` works, but it doesn't matter for this program):
|
||||
|
||||
::
|
||||
|
||||
[a b c] dup
|
||||
[a b c] [a b c] uncons swap
|
||||
[a b c] [b c] a unit concat
|
||||
[a b c] [b c a] zip
|
||||
[[b a] [c b] [a c]]
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('pair_up == dup uncons swap unit concat zip')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 3] pair_up')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[[2 1] [3 2] [1 3]]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 2 3] pair_up')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[[2 1] [2 2] [3 2] [1 3]]
|
||||
|
||||
|
||||
Now we need to derive ``total_matches``. It will be a ``step`` function:
|
||||
|
||||
::
|
||||
|
||||
total_matches == 0 swap [F] step
|
||||
|
||||
Where ``F`` will have the pair to work with, and it will basically be a
|
||||
``branch`` or ``ifte``.
|
||||
|
||||
::
|
||||
|
||||
total [n m] F
|
||||
|
||||
It will probably be easier to write if we dequote the pair:
|
||||
|
||||
::
|
||||
|
||||
total [n m] i F′
|
||||
----------------------
|
||||
total n m F′
|
||||
|
||||
Now ``F′`` becomes just:
|
||||
|
||||
::
|
||||
|
||||
total n m [=] [pop +] [popop] ifte
|
||||
|
||||
So:
|
||||
|
||||
::
|
||||
|
||||
F == i [=] [pop +] [popop] ifte
|
||||
|
||||
And thus:
|
||||
|
||||
::
|
||||
|
||||
total_matches == 0 swap [i [=] [pop +] [popop] ifte] step
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('total_matches == 0 swap [i [=] [pop +] [popop] ifte] step')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 3] pair_up total_matches')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
0
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 2 3] pair_up total_matches')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2
|
||||
|
||||
|
||||
Now we can define our main program and evaluate it on the examples.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('AoC2017.1 == pair_up total_matches')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 1 2 2] AoC2017.1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 1 1 1] AoC2017.1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
4
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 3 4] AoC2017.1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
0
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[9 1 2 1 2 1 2 9] AoC2017.1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
9
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[9 1 2 1 2 1 2 9] AoC2017.1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
9
|
||||
|
||||
|
||||
::
|
||||
|
||||
pair_up == dup uncons swap unit concat zip
|
||||
total_matches == 0 swap [i [=] [pop +] [popop] ifte] step
|
||||
|
||||
AoC2017.1 == pair_up total_matches
|
||||
|
||||
Now the paired digit is "halfway" round.
|
||||
|
||||
::
|
||||
|
||||
[a b c d] dup size 2 / [drop] [take reverse] cleave concat zip
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave concat zip')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[[3 1] [4 2] [1 3] [2 4]]
|
||||
|
||||
|
||||
I realized that each pair is repeated...
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave zip')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[1 2 3 4] [[1 3] [2 4]]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('AoC2017.1.extra == dup size 2 / [drop] [take reverse] cleave zip swap pop total_matches 2 *')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 1 2] AoC2017.1.extra')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
6
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 2 1] AoC2017.1.extra')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
0
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 3 4 2 5] AoC2017.1.extra')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
4
|
||||
|
||||
|
||||
Refactor FTW
|
||||
============
|
||||
|
||||
With Joy a great deal of the heuristics from Forth programming carry
|
||||
over nicely. For example, refactoring into small, well-scoped commands
|
||||
with mnemonic names...
|
||||
|
||||
::
|
||||
|
||||
rotate_seq == uncons swap unit concat
|
||||
pair_up == dup rotate_seq zip
|
||||
add_if_match == [=] [pop +] [popop] ifte
|
||||
total_matches == [i add_if_match] step_zero
|
||||
|
||||
AoC2017.1 == pair_up total_matches
|
||||
|
||||
half_of_size == dup size 2 /
|
||||
split_at == [drop] [take reverse] cleave
|
||||
pair_up.extra == half_of_size split_at zip swap pop
|
||||
|
||||
AoC2017.1.extra == pair_up.extra total_matches 2 *
|
||||
|
|
@ -1,554 +0,0 @@
|
|||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Advent of Code 2017\n",
|
||||
"\n",
|
||||
"## December 2nd\n",
|
||||
"\n",
|
||||
"For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences.\n",
|
||||
"\n",
|
||||
"For example, given the following spreadsheet:\n",
|
||||
"\n",
|
||||
" 5 1 9 5\n",
|
||||
" 7 5 3\n",
|
||||
" 2 4 6 8\n",
|
||||
"\n",
|
||||
"* The first row's largest and smallest values are 9 and 1, and their difference is 8.\n",
|
||||
"* The second row's largest and smallest values are 7 and 3, and their difference is 4.\n",
|
||||
"* The third row's difference is 6.\n",
|
||||
"\n",
|
||||
"In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from notebook_preamble import J, V, define"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"I'll assume the input is a Joy sequence of sequences of integers.\n",
|
||||
"\n",
|
||||
" [[5 1 9 5]\n",
|
||||
" [7 5 3]\n",
|
||||
" [2 4 6 8]]\n",
|
||||
"\n",
|
||||
"So, obviously, the initial form will be a `step` function:\n",
|
||||
"\n",
|
||||
" AoC2017.2 == 0 swap [F +] step"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This function `F` must get the `max` and `min` of a row of numbers and subtract. We can define a helper function `maxmin` which does this:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('maxmin == [max] [min] cleave')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"3 1\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 2 3] maxmin')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then `F` just does that then subtracts the min from the max:\n",
|
||||
"\n",
|
||||
" F == maxmin -\n",
|
||||
"\n",
|
||||
"So:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('AoC2017.2 == [maxmin - +] step_zero')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"18\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('''\n",
|
||||
"\n",
|
||||
"[[5 1 9 5]\n",
|
||||
" [7 5 3]\n",
|
||||
" [2 4 6 8]] AoC2017.2\n",
|
||||
"\n",
|
||||
"''')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"...find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result.\n",
|
||||
"\n",
|
||||
"For example, given the following spreadsheet:\n",
|
||||
"\n",
|
||||
" 5 9 2 8\n",
|
||||
" 9 4 7 3\n",
|
||||
" 3 8 6 5\n",
|
||||
"\n",
|
||||
"* In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.\n",
|
||||
"* In the second row, the two numbers are 9 and 3; the result is 3.\n",
|
||||
"* In the third row, the result is 2.\n",
|
||||
"\n",
|
||||
"In this example, the sum of the results would be 4 + 3 + 2 = 9.\n",
|
||||
"\n",
|
||||
"What is the sum of each row's result in your puzzle input?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[9 8 5 2]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[5 9 2 8] sort reverse')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[8 5 2] [9 divmod] [8 5 2]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[9 8 5 2] uncons [swap [divmod] cons] dupdip')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
" [9 8 5 2] uncons [swap [divmod] cons F] dupdip G\n",
|
||||
" [8 5 2] [9 divmod] F [8 5 2] G\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
" . [8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip\n",
|
||||
" [8 5 2] . [9 divmod] [uncons swap] dip dup [i not] dip\n",
|
||||
" [8 5 2] [9 divmod] . [uncons swap] dip dup [i not] dip\n",
|
||||
" [8 5 2] [9 divmod] [uncons swap] . dip dup [i not] dip\n",
|
||||
" [8 5 2] . uncons swap [9 divmod] dup [i not] dip\n",
|
||||
" 8 [5 2] . swap [9 divmod] dup [i not] dip\n",
|
||||
" [5 2] 8 . [9 divmod] dup [i not] dip\n",
|
||||
" [5 2] 8 [9 divmod] . dup [i not] dip\n",
|
||||
" [5 2] 8 [9 divmod] [9 divmod] . [i not] dip\n",
|
||||
"[5 2] 8 [9 divmod] [9 divmod] [i not] . dip\n",
|
||||
" [5 2] 8 [9 divmod] . i not [9 divmod]\n",
|
||||
" [5 2] 8 . 9 divmod not [9 divmod]\n",
|
||||
" [5 2] 8 9 . divmod not [9 divmod]\n",
|
||||
" [5 2] 1 1 . not [9 divmod]\n",
|
||||
" [5 2] 1 False . [9 divmod]\n",
|
||||
" [5 2] 1 False [9 divmod] . \n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"V('[8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Tricky\n",
|
||||
"\n",
|
||||
"Let's think.\n",
|
||||
"\n",
|
||||
"Given a *sorted* sequence (from highest to lowest) we want to \n",
|
||||
"* for head, tail in sequence\n",
|
||||
" * for term in tail:\n",
|
||||
" * check if the head % term == 0\n",
|
||||
" * if so compute head / term and terminate loop\n",
|
||||
" * else continue"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### So we want a `loop` I think\n",
|
||||
"\n",
|
||||
" [a b c d] True [Q] loop\n",
|
||||
" [a b c d] Q [Q] loop\n",
|
||||
"\n",
|
||||
"`Q` should either leave the result and False, or the `rest` and True.\n",
|
||||
"\n",
|
||||
" [a b c d] Q\n",
|
||||
" -----------------\n",
|
||||
" result 0\n",
|
||||
"\n",
|
||||
" [a b c d] Q\n",
|
||||
" -----------------\n",
|
||||
" [b c d] 1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This suggests that `Q` should start with:\n",
|
||||
"\n",
|
||||
" [a b c d] uncons dup roll<\n",
|
||||
" [b c d] [b c d] a\n",
|
||||
"\n",
|
||||
"Now we just have to `pop` it if we don't need it.\n",
|
||||
"\n",
|
||||
" [b c d] [b c d] a [P] [T] [cons] app2 popdd [E] primrec\n",
|
||||
" [b c d] [b c d] [a P] [a T] [E] primrec\n",
|
||||
"\n",
|
||||
"-------------------\n",
|
||||
"\n",
|
||||
" w/ Q == [% not] [T] [F] primrec\n",
|
||||
"\n",
|
||||
" [a b c d] uncons\n",
|
||||
" a [b c d] tuck\n",
|
||||
" [b c d] a [b c d] uncons\n",
|
||||
" [b c d] a b [c d] roll>\n",
|
||||
" [b c d] [c d] a b Q\n",
|
||||
" [b c d] [c d] a b [% not] [T] [F] primrec\n",
|
||||
"\n",
|
||||
" [b c d] [c d] a b T\n",
|
||||
" [b c d] [c d] a b / roll> popop 0\n",
|
||||
"\n",
|
||||
" [b c d] [c d] a b F Q\n",
|
||||
" [b c d] [c d] a b pop swap uncons ... Q\n",
|
||||
" [b c d] [c d] a swap uncons ... Q\n",
|
||||
" [b c d] a [c d] uncons ... Q\n",
|
||||
" [b c d] a c [d] roll> Q\n",
|
||||
" [b c d] [d] a c Q\n",
|
||||
"\n",
|
||||
" Q == [% not] [/ roll> popop 0] [pop swap uncons roll>] primrec\n",
|
||||
" \n",
|
||||
" uncons tuck uncons roll> Q"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[8 5 3 2] [9 swap] [9 % not]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[8 5 3 2] 9 [swap] [% not] [cons] app2 popdd')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"-------------------\n",
|
||||
"\n",
|
||||
" [a b c d] uncons\n",
|
||||
" a [b c d] tuck\n",
|
||||
" [b c d] a [b c d] [not] [popop 1] [Q] ifte\n",
|
||||
"\n",
|
||||
" [b c d] a [] popop 1\n",
|
||||
" [b c d] 1\n",
|
||||
"\n",
|
||||
" [b c d] a [b c d] Q \n",
|
||||
"\n",
|
||||
"\n",
|
||||
" a [...] Q\n",
|
||||
" ---------------\n",
|
||||
" result 0\n",
|
||||
"\n",
|
||||
" a [...] Q\n",
|
||||
" ---------------\n",
|
||||
" 1\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" w/ Q == [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||
" a [b c d] first % not\n",
|
||||
" a b % not\n",
|
||||
" a%b not\n",
|
||||
" bool(a%b)\n",
|
||||
"\n",
|
||||
" a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||
" a [b c d] first / 0\n",
|
||||
" a b / 0\n",
|
||||
" a/b 0\n",
|
||||
"\n",
|
||||
" a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||
" a [b c d] rest [not] [popop 1] [Q] ifte\n",
|
||||
" a [c d] [not] [popop 1] [Q] ifte\n",
|
||||
" a [c d] [not] [popop 1] [Q] ifte\n",
|
||||
"\n",
|
||||
" a [c d] [not] [popop 1] [Q] ifte\n",
|
||||
" a [c d] not\n",
|
||||
"\n",
|
||||
" a [] popop 1\n",
|
||||
" 1\n",
|
||||
"\n",
|
||||
" a [c d] Q\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" uncons tuck [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||
" \n",
|
||||
" \n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### I finally sat down with a piece of paper and blocked it out.\n",
|
||||
"\n",
|
||||
"First, I made a function `G` that expects a number and a sequence of candidates and return the result or zero:\n",
|
||||
"\n",
|
||||
" n [...] G\n",
|
||||
" ---------------\n",
|
||||
" result\n",
|
||||
"\n",
|
||||
" n [...] G\n",
|
||||
" ---------------\n",
|
||||
" 0\n",
|
||||
"\n",
|
||||
"It's a recursive function that conditionally executes the recursive part of its recursive branch\n",
|
||||
"\n",
|
||||
" [Pg] [E] [R1 [Pi] [T]] [ifte] genrec\n",
|
||||
"\n",
|
||||
"The recursive branch is the else-part of the inner `ifte`:\n",
|
||||
"\n",
|
||||
" G == [Pg] [E] [R1 [Pi] [T]] [ifte] genrec\n",
|
||||
" == [Pg] [E] [R1 [Pi] [T] [G] ifte] ifte\n",
|
||||
"\n",
|
||||
"But this is in hindsight. Going forward I derived:\n",
|
||||
"\n",
|
||||
" G == [first % not]\n",
|
||||
" [first /]\n",
|
||||
" [rest [not] [popop 0]]\n",
|
||||
" [ifte] genrec\n",
|
||||
"\n",
|
||||
"The predicate detects if the `n` can be evenly divided by the `first` item in the list. If so, the then-part returns the result. Otherwise, we have:\n",
|
||||
"\n",
|
||||
" n [m ...] rest [not] [popop 0] [G] ifte\n",
|
||||
" n [...] [not] [popop 0] [G] ifte\n",
|
||||
"\n",
|
||||
"This `ifte` guards against empty sequences and returns zero in that case, otherwise it executes `G`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('G == [first % not] [first /] [rest [not] [popop 0]] [ifte] genrec')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we need a word that uses `G` on each (head, tail) pair of a sequence until it finds a (non-zero) result. It's going to be designed to work on a stack that has some candidate `n`, a sequence of possible divisors, and a result that is zero to signal to continue (a non-zero value implies that it is the discovered result):\n",
|
||||
"\n",
|
||||
" n [...] p find-result\n",
|
||||
" ---------------------------\n",
|
||||
" result\n",
|
||||
"\n",
|
||||
"It applies `G` using `nullary` because if it fails with one candidate it needs the list to get the next one (the list is otherwise consumed by `G`.)\n",
|
||||
"\n",
|
||||
" find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec\n",
|
||||
"\n",
|
||||
" n [...] p [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec\n",
|
||||
"\n",
|
||||
"The base-case is trivial, return the (non-zero) result. The recursive branch...\n",
|
||||
"\n",
|
||||
" n [...] p roll< popop uncons [G] nullary find-result\n",
|
||||
" [...] p n popop uncons [G] nullary find-result\n",
|
||||
" [...] uncons [G] nullary find-result\n",
|
||||
" m [..] [G] nullary find-result\n",
|
||||
" m [..] p find-result\n",
|
||||
"\n",
|
||||
"The puzzle states that the input is well-formed, meaning that we can expect a result before the row sequence empties and so do not need to guard the `uncons`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 14,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"3.0\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[11 9 8 7 3 2] 0 tuck find-result')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"In order to get the thing started, we need to `sort` the list in descending order, then prime the `find-result` function with a dummy candidate value and zero (\"continue\") flag."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('prep-row == sort reverse 0 tuck')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we can define our program."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 13,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('AoC20017.2.extra == [prep-row find-result +] step_zero')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"9.0\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('''\n",
|
||||
"\n",
|
||||
"[[5 9 2 8]\n",
|
||||
" [9 4 7 3]\n",
|
||||
" [3 8 6 5]] AoC20017.2.extra\n",
|
||||
"\n",
|
||||
"''')"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
|
|
@ -1,361 +0,0 @@
|
|||
|
||||
# Advent of Code 2017
|
||||
|
||||
## December 2nd
|
||||
|
||||
For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences.
|
||||
|
||||
For example, given the following spreadsheet:
|
||||
|
||||
5 1 9 5
|
||||
7 5 3
|
||||
2 4 6 8
|
||||
|
||||
* The first row's largest and smallest values are 9 and 1, and their difference is 8.
|
||||
* The second row's largest and smallest values are 7 and 3, and their difference is 4.
|
||||
* The third row's difference is 6.
|
||||
|
||||
In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18.
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import J, V, define
|
||||
```
|
||||
|
||||
I'll assume the input is a Joy sequence of sequences of integers.
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 3]
|
||||
[2 4 6 8]]
|
||||
|
||||
So, obviously, the initial form will be a `step` function:
|
||||
|
||||
AoC2017.2 == 0 swap [F +] step
|
||||
|
||||
This function `F` must get the `max` and `min` of a row of numbers and subtract. We can define a helper function `maxmin` which does this:
|
||||
|
||||
|
||||
```python
|
||||
define('maxmin == [max] [min] cleave')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[1 2 3] maxmin')
|
||||
```
|
||||
|
||||
3 1
|
||||
|
||||
|
||||
Then `F` just does that then subtracts the min from the max:
|
||||
|
||||
F == maxmin -
|
||||
|
||||
So:
|
||||
|
||||
|
||||
```python
|
||||
define('AoC2017.2 == [maxmin - +] step_zero')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('''
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 3]
|
||||
[2 4 6 8]] AoC2017.2
|
||||
|
||||
''')
|
||||
```
|
||||
|
||||
18
|
||||
|
||||
|
||||
...find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result.
|
||||
|
||||
For example, given the following spreadsheet:
|
||||
|
||||
5 9 2 8
|
||||
9 4 7 3
|
||||
3 8 6 5
|
||||
|
||||
* In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.
|
||||
* In the second row, the two numbers are 9 and 3; the result is 3.
|
||||
* In the third row, the result is 2.
|
||||
|
||||
In this example, the sum of the results would be 4 + 3 + 2 = 9.
|
||||
|
||||
What is the sum of each row's result in your puzzle input?
|
||||
|
||||
|
||||
```python
|
||||
J('[5 9 2 8] sort reverse')
|
||||
```
|
||||
|
||||
[9 8 5 2]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[9 8 5 2] uncons [swap [divmod] cons] dupdip')
|
||||
```
|
||||
|
||||
[8 5 2] [9 divmod] [8 5 2]
|
||||
|
||||
|
||||
|
||||
[9 8 5 2] uncons [swap [divmod] cons F] dupdip G
|
||||
[8 5 2] [9 divmod] F [8 5 2] G
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
V('[8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip')
|
||||
```
|
||||
|
||||
. [8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip
|
||||
[8 5 2] . [9 divmod] [uncons swap] dip dup [i not] dip
|
||||
[8 5 2] [9 divmod] . [uncons swap] dip dup [i not] dip
|
||||
[8 5 2] [9 divmod] [uncons swap] . dip dup [i not] dip
|
||||
[8 5 2] . uncons swap [9 divmod] dup [i not] dip
|
||||
8 [5 2] . swap [9 divmod] dup [i not] dip
|
||||
[5 2] 8 . [9 divmod] dup [i not] dip
|
||||
[5 2] 8 [9 divmod] . dup [i not] dip
|
||||
[5 2] 8 [9 divmod] [9 divmod] . [i not] dip
|
||||
[5 2] 8 [9 divmod] [9 divmod] [i not] . dip
|
||||
[5 2] 8 [9 divmod] . i not [9 divmod]
|
||||
[5 2] 8 . 9 divmod not [9 divmod]
|
||||
[5 2] 8 9 . divmod not [9 divmod]
|
||||
[5 2] 1 1 . not [9 divmod]
|
||||
[5 2] 1 False . [9 divmod]
|
||||
[5 2] 1 False [9 divmod] .
|
||||
|
||||
|
||||
## Tricky
|
||||
|
||||
Let's think.
|
||||
|
||||
Given a *sorted* sequence (from highest to lowest) we want to
|
||||
* for head, tail in sequence
|
||||
* for term in tail:
|
||||
* check if the head % term == 0
|
||||
* if so compute head / term and terminate loop
|
||||
* else continue
|
||||
|
||||
### So we want a `loop` I think
|
||||
|
||||
[a b c d] True [Q] loop
|
||||
[a b c d] Q [Q] loop
|
||||
|
||||
`Q` should either leave the result and False, or the `rest` and True.
|
||||
|
||||
[a b c d] Q
|
||||
-----------------
|
||||
result 0
|
||||
|
||||
[a b c d] Q
|
||||
-----------------
|
||||
[b c d] 1
|
||||
|
||||
This suggests that `Q` should start with:
|
||||
|
||||
[a b c d] uncons dup roll<
|
||||
[b c d] [b c d] a
|
||||
|
||||
Now we just have to `pop` it if we don't need it.
|
||||
|
||||
[b c d] [b c d] a [P] [T] [cons] app2 popdd [E] primrec
|
||||
[b c d] [b c d] [a P] [a T] [E] primrec
|
||||
|
||||
-------------------
|
||||
|
||||
w/ Q == [% not] [T] [F] primrec
|
||||
|
||||
[a b c d] uncons
|
||||
a [b c d] tuck
|
||||
[b c d] a [b c d] uncons
|
||||
[b c d] a b [c d] roll>
|
||||
[b c d] [c d] a b Q
|
||||
[b c d] [c d] a b [% not] [T] [F] primrec
|
||||
|
||||
[b c d] [c d] a b T
|
||||
[b c d] [c d] a b / roll> popop 0
|
||||
|
||||
[b c d] [c d] a b F Q
|
||||
[b c d] [c d] a b pop swap uncons ... Q
|
||||
[b c d] [c d] a swap uncons ... Q
|
||||
[b c d] a [c d] uncons ... Q
|
||||
[b c d] a c [d] roll> Q
|
||||
[b c d] [d] a c Q
|
||||
|
||||
Q == [% not] [/ roll> popop 0] [pop swap uncons roll>] primrec
|
||||
|
||||
uncons tuck uncons roll> Q
|
||||
|
||||
|
||||
```python
|
||||
J('[8 5 3 2] 9 [swap] [% not] [cons] app2 popdd')
|
||||
```
|
||||
|
||||
[8 5 3 2] [9 swap] [9 % not]
|
||||
|
||||
|
||||
-------------------
|
||||
|
||||
[a b c d] uncons
|
||||
a [b c d] tuck
|
||||
[b c d] a [b c d] [not] [popop 1] [Q] ifte
|
||||
|
||||
[b c d] a [] popop 1
|
||||
[b c d] 1
|
||||
|
||||
[b c d] a [b c d] Q
|
||||
|
||||
|
||||
a [...] Q
|
||||
---------------
|
||||
result 0
|
||||
|
||||
a [...] Q
|
||||
---------------
|
||||
1
|
||||
|
||||
|
||||
w/ Q == [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
|
||||
|
||||
|
||||
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
a [b c d] first % not
|
||||
a b % not
|
||||
a%b not
|
||||
bool(a%b)
|
||||
|
||||
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
a [b c d] first / 0
|
||||
a b / 0
|
||||
a/b 0
|
||||
|
||||
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
a [b c d] rest [not] [popop 1] [Q] ifte
|
||||
a [c d] [not] [popop 1] [Q] ifte
|
||||
a [c d] [not] [popop 1] [Q] ifte
|
||||
|
||||
a [c d] [not] [popop 1] [Q] ifte
|
||||
a [c d] not
|
||||
|
||||
a [] popop 1
|
||||
1
|
||||
|
||||
a [c d] Q
|
||||
|
||||
|
||||
uncons tuck [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
|
||||
|
||||
|
||||
|
||||
### I finally sat down with a piece of paper and blocked it out.
|
||||
|
||||
First, I made a function `G` that expects a number and a sequence of candidates and return the result or zero:
|
||||
|
||||
n [...] G
|
||||
---------------
|
||||
result
|
||||
|
||||
n [...] G
|
||||
---------------
|
||||
0
|
||||
|
||||
It's a recursive function that conditionally executes the recursive part of its recursive branch
|
||||
|
||||
[Pg] [E] [R1 [Pi] [T]] [ifte] genrec
|
||||
|
||||
The recursive branch is the else-part of the inner `ifte`:
|
||||
|
||||
G == [Pg] [E] [R1 [Pi] [T]] [ifte] genrec
|
||||
== [Pg] [E] [R1 [Pi] [T] [G] ifte] ifte
|
||||
|
||||
But this is in hindsight. Going forward I derived:
|
||||
|
||||
G == [first % not]
|
||||
[first /]
|
||||
[rest [not] [popop 0]]
|
||||
[ifte] genrec
|
||||
|
||||
The predicate detects if the `n` can be evenly divided by the `first` item in the list. If so, the then-part returns the result. Otherwise, we have:
|
||||
|
||||
n [m ...] rest [not] [popop 0] [G] ifte
|
||||
n [...] [not] [popop 0] [G] ifte
|
||||
|
||||
This `ifte` guards against empty sequences and returns zero in that case, otherwise it executes `G`.
|
||||
|
||||
|
||||
```python
|
||||
define('G == [first % not] [first /] [rest [not] [popop 0]] [ifte] genrec')
|
||||
```
|
||||
|
||||
Now we need a word that uses `G` on each (head, tail) pair of a sequence until it finds a (non-zero) result. It's going to be designed to work on a stack that has some candidate `n`, a sequence of possible divisors, and a result that is zero to signal to continue (a non-zero value implies that it is the discovered result):
|
||||
|
||||
n [...] p find-result
|
||||
---------------------------
|
||||
result
|
||||
|
||||
It applies `G` using `nullary` because if it fails with one candidate it needs the list to get the next one (the list is otherwise consumed by `G`.)
|
||||
|
||||
find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec
|
||||
|
||||
n [...] p [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec
|
||||
|
||||
The base-case is trivial, return the (non-zero) result. The recursive branch...
|
||||
|
||||
n [...] p roll< popop uncons [G] nullary find-result
|
||||
[...] p n popop uncons [G] nullary find-result
|
||||
[...] uncons [G] nullary find-result
|
||||
m [..] [G] nullary find-result
|
||||
m [..] p find-result
|
||||
|
||||
The puzzle states that the input is well-formed, meaning that we can expect a result before the row sequence empties and so do not need to guard the `uncons`.
|
||||
|
||||
|
||||
```python
|
||||
define('find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[11 9 8 7 3 2] 0 tuck find-result')
|
||||
```
|
||||
|
||||
3.0
|
||||
|
||||
|
||||
In order to get the thing started, we need to `sort` the list in descending order, then prime the `find-result` function with a dummy candidate value and zero ("continue") flag.
|
||||
|
||||
|
||||
```python
|
||||
define('prep-row == sort reverse 0 tuck')
|
||||
```
|
||||
|
||||
Now we can define our program.
|
||||
|
||||
|
||||
```python
|
||||
define('AoC20017.2.extra == [prep-row find-result +] step_zero')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('''
|
||||
|
||||
[[5 9 2 8]
|
||||
[9 4 7 3]
|
||||
[3 8 6 5]] AoC20017.2.extra
|
||||
|
||||
''')
|
||||
```
|
||||
|
||||
9.0
|
||||
|
||||
|
|
@ -1,432 +0,0 @@
|
|||
|
||||
Advent of Code 2017
|
||||
===================
|
||||
|
||||
December 2nd
|
||||
------------
|
||||
|
||||
For each row, determine the difference between the largest value and the
|
||||
smallest value; the checksum is the sum of all of these differences.
|
||||
|
||||
For example, given the following spreadsheet:
|
||||
|
||||
::
|
||||
|
||||
5 1 9 5
|
||||
7 5 3
|
||||
2 4 6 8
|
||||
|
||||
- The first row's largest and smallest values are 9 and 1, and their
|
||||
difference is 8.
|
||||
- The second row's largest and smallest values are 7 and 3, and their
|
||||
difference is 4.
|
||||
- The third row's difference is 6.
|
||||
|
||||
In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import J, V, define
|
||||
|
||||
I'll assume the input is a Joy sequence of sequences of integers.
|
||||
|
||||
::
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 3]
|
||||
[2 4 6 8]]
|
||||
|
||||
So, obviously, the initial form will be a ``step`` function:
|
||||
|
||||
::
|
||||
|
||||
AoC2017.2 == 0 swap [F +] step
|
||||
|
||||
This function ``F`` must get the ``max`` and ``min`` of a row of numbers
|
||||
and subtract. We can define a helper function ``maxmin`` which does
|
||||
this:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('maxmin == [max] [min] cleave')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 2 3] maxmin')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3 1
|
||||
|
||||
|
||||
Then ``F`` just does that then subtracts the min from the max:
|
||||
|
||||
::
|
||||
|
||||
F == maxmin -
|
||||
|
||||
So:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('AoC2017.2 == [maxmin - +] step_zero')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('''
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 3]
|
||||
[2 4 6 8]] AoC2017.2
|
||||
|
||||
''')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
18
|
||||
|
||||
|
||||
...find the only two numbers in each row where one evenly divides the
|
||||
other - that is, where the result of the division operation is a whole
|
||||
number. They would like you to find those numbers on each line, divide
|
||||
them, and add up each line's result.
|
||||
|
||||
For example, given the following spreadsheet:
|
||||
|
||||
::
|
||||
|
||||
5 9 2 8
|
||||
9 4 7 3
|
||||
3 8 6 5
|
||||
|
||||
- In the first row, the only two numbers that evenly divide are 8 and
|
||||
2; the result of this division is 4.
|
||||
- In the second row, the two numbers are 9 and 3; the result is 3.
|
||||
- In the third row, the result is 2.
|
||||
|
||||
In this example, the sum of the results would be 4 + 3 + 2 = 9.
|
||||
|
||||
What is the sum of each row's result in your puzzle input?
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[5 9 2 8] sort reverse')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[9 8 5 2]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[9 8 5 2] uncons [swap [divmod] cons] dupdip')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[8 5 2] [9 divmod] [8 5 2]
|
||||
|
||||
|
||||
::
|
||||
|
||||
[9 8 5 2] uncons [swap [divmod] cons F] dupdip G
|
||||
[8 5 2] [9 divmod] F [8 5 2] G
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('[8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. [8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip
|
||||
[8 5 2] . [9 divmod] [uncons swap] dip dup [i not] dip
|
||||
[8 5 2] [9 divmod] . [uncons swap] dip dup [i not] dip
|
||||
[8 5 2] [9 divmod] [uncons swap] . dip dup [i not] dip
|
||||
[8 5 2] . uncons swap [9 divmod] dup [i not] dip
|
||||
8 [5 2] . swap [9 divmod] dup [i not] dip
|
||||
[5 2] 8 . [9 divmod] dup [i not] dip
|
||||
[5 2] 8 [9 divmod] . dup [i not] dip
|
||||
[5 2] 8 [9 divmod] [9 divmod] . [i not] dip
|
||||
[5 2] 8 [9 divmod] [9 divmod] [i not] . dip
|
||||
[5 2] 8 [9 divmod] . i not [9 divmod]
|
||||
[5 2] 8 . 9 divmod not [9 divmod]
|
||||
[5 2] 8 9 . divmod not [9 divmod]
|
||||
[5 2] 1 1 . not [9 divmod]
|
||||
[5 2] 1 False . [9 divmod]
|
||||
[5 2] 1 False [9 divmod] .
|
||||
|
||||
|
||||
Tricky
|
||||
------
|
||||
|
||||
Let's think.
|
||||
|
||||
Given a *sorted* sequence (from highest to lowest) we want to \* for
|
||||
head, tail in sequence \* for term in tail: \* check if the head % term
|
||||
== 0 \* if so compute head / term and terminate loop \* else continue
|
||||
|
||||
So we want a ``loop`` I think
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
[a b c d] True [Q] loop
|
||||
[a b c d] Q [Q] loop
|
||||
|
||||
``Q`` should either leave the result and False, or the ``rest`` and
|
||||
True.
|
||||
|
||||
::
|
||||
|
||||
[a b c d] Q
|
||||
-----------------
|
||||
result 0
|
||||
|
||||
[a b c d] Q
|
||||
-----------------
|
||||
[b c d] 1
|
||||
|
||||
This suggests that ``Q`` should start with:
|
||||
|
||||
::
|
||||
|
||||
[a b c d] uncons dup roll<
|
||||
[b c d] [b c d] a
|
||||
|
||||
Now we just have to ``pop`` it if we don't need it.
|
||||
|
||||
::
|
||||
|
||||
[b c d] [b c d] a [P] [T] [cons] app2 popdd [E] primrec
|
||||
[b c d] [b c d] [a P] [a T] [E] primrec
|
||||
|
||||
--------------
|
||||
|
||||
::
|
||||
|
||||
w/ Q == [% not] [T] [F] primrec
|
||||
|
||||
[a b c d] uncons
|
||||
a [b c d] tuck
|
||||
[b c d] a [b c d] uncons
|
||||
[b c d] a b [c d] roll>
|
||||
[b c d] [c d] a b Q
|
||||
[b c d] [c d] a b [% not] [T] [F] primrec
|
||||
|
||||
[b c d] [c d] a b T
|
||||
[b c d] [c d] a b / roll> popop 0
|
||||
|
||||
[b c d] [c d] a b F Q
|
||||
[b c d] [c d] a b pop swap uncons ... Q
|
||||
[b c d] [c d] a swap uncons ... Q
|
||||
[b c d] a [c d] uncons ... Q
|
||||
[b c d] a c [d] roll> Q
|
||||
[b c d] [d] a c Q
|
||||
|
||||
Q == [% not] [/ roll> popop 0] [pop swap uncons roll>] primrec
|
||||
|
||||
uncons tuck uncons roll> Q
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[8 5 3 2] 9 [swap] [% not] [cons] app2 popdd')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[8 5 3 2] [9 swap] [9 % not]
|
||||
|
||||
|
||||
--------------
|
||||
|
||||
::
|
||||
|
||||
[a b c d] uncons
|
||||
a [b c d] tuck
|
||||
[b c d] a [b c d] [not] [popop 1] [Q] ifte
|
||||
|
||||
[b c d] a [] popop 1
|
||||
[b c d] 1
|
||||
|
||||
[b c d] a [b c d] Q
|
||||
|
||||
|
||||
a [...] Q
|
||||
---------------
|
||||
result 0
|
||||
|
||||
a [...] Q
|
||||
---------------
|
||||
1
|
||||
|
||||
|
||||
w/ Q == [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
|
||||
|
||||
|
||||
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
a [b c d] first % not
|
||||
a b % not
|
||||
a%b not
|
||||
bool(a%b)
|
||||
|
||||
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
a [b c d] first / 0
|
||||
a b / 0
|
||||
a/b 0
|
||||
|
||||
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
a [b c d] rest [not] [popop 1] [Q] ifte
|
||||
a [c d] [not] [popop 1] [Q] ifte
|
||||
a [c d] [not] [popop 1] [Q] ifte
|
||||
|
||||
a [c d] [not] [popop 1] [Q] ifte
|
||||
a [c d] not
|
||||
|
||||
a [] popop 1
|
||||
1
|
||||
|
||||
a [c d] Q
|
||||
|
||||
|
||||
uncons tuck [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||
|
||||
I finally sat down with a piece of paper and blocked it out.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
First, I made a function ``G`` that expects a number and a sequence of
|
||||
candidates and return the result or zero:
|
||||
|
||||
::
|
||||
|
||||
n [...] G
|
||||
---------------
|
||||
result
|
||||
|
||||
n [...] G
|
||||
---------------
|
||||
0
|
||||
|
||||
It's a recursive function that conditionally executes the recursive part
|
||||
of its recursive branch
|
||||
|
||||
::
|
||||
|
||||
[Pg] [E] [R1 [Pi] [T]] [ifte] genrec
|
||||
|
||||
The recursive branch is the else-part of the inner ``ifte``:
|
||||
|
||||
::
|
||||
|
||||
G == [Pg] [E] [R1 [Pi] [T]] [ifte] genrec
|
||||
== [Pg] [E] [R1 [Pi] [T] [G] ifte] ifte
|
||||
|
||||
But this is in hindsight. Going forward I derived:
|
||||
|
||||
::
|
||||
|
||||
G == [first % not]
|
||||
[first /]
|
||||
[rest [not] [popop 0]]
|
||||
[ifte] genrec
|
||||
|
||||
The predicate detects if the ``n`` can be evenly divided by the
|
||||
``first`` item in the list. If so, the then-part returns the result.
|
||||
Otherwise, we have:
|
||||
|
||||
::
|
||||
|
||||
n [m ...] rest [not] [popop 0] [G] ifte
|
||||
n [...] [not] [popop 0] [G] ifte
|
||||
|
||||
This ``ifte`` guards against empty sequences and returns zero in that
|
||||
case, otherwise it executes ``G``.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('G == [first % not] [first /] [rest [not] [popop 0]] [ifte] genrec')
|
||||
|
||||
Now we need a word that uses ``G`` on each (head, tail) pair of a
|
||||
sequence until it finds a (non-zero) result. It's going to be designed
|
||||
to work on a stack that has some candidate ``n``, a sequence of possible
|
||||
divisors, and a result that is zero to signal to continue (a non-zero
|
||||
value implies that it is the discovered result):
|
||||
|
||||
::
|
||||
|
||||
n [...] p find-result
|
||||
---------------------------
|
||||
result
|
||||
|
||||
It applies ``G`` using ``nullary`` because if it fails with one
|
||||
candidate it needs the list to get the next one (the list is otherwise
|
||||
consumed by ``G``.)
|
||||
|
||||
::
|
||||
|
||||
find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec
|
||||
|
||||
n [...] p [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec
|
||||
|
||||
The base-case is trivial, return the (non-zero) result. The recursive
|
||||
branch...
|
||||
|
||||
::
|
||||
|
||||
n [...] p roll< popop uncons [G] nullary find-result
|
||||
[...] p n popop uncons [G] nullary find-result
|
||||
[...] uncons [G] nullary find-result
|
||||
m [..] [G] nullary find-result
|
||||
m [..] p find-result
|
||||
|
||||
The puzzle states that the input is well-formed, meaning that we can
|
||||
expect a result before the row sequence empties and so do not need to
|
||||
guard the ``uncons``.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[11 9 8 7 3 2] 0 tuck find-result')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3.0
|
||||
|
||||
|
||||
In order to get the thing started, we need to ``sort`` the list in
|
||||
descending order, then prime the ``find-result`` function with a dummy
|
||||
candidate value and zero ("continue") flag.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('prep-row == sort reverse 0 tuck')
|
||||
|
||||
Now we can define our program.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('AoC20017.2.extra == [prep-row find-result +] step_zero')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('''
|
||||
|
||||
[[5 9 2 8]
|
||||
[9 4 7 3]
|
||||
[3 8 6 5]] AoC20017.2.extra
|
||||
|
||||
''')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
9.0
|
||||
|
||||
|
|
@ -1,843 +0,0 @@
|
|||
|
||||
# Advent of Code 2017
|
||||
|
||||
## December 3rd
|
||||
|
||||
You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
|
||||
|
||||
Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this:
|
||||
|
||||
17 16 15 14 13
|
||||
18 5 4 3 12
|
||||
19 6 1 2 11
|
||||
20 7 8 9 10
|
||||
21 22 23---> ...
|
||||
|
||||
While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1.
|
||||
|
||||
For example:
|
||||
|
||||
* Data from square 1 is carried 0 steps, since it's at the access port.
|
||||
* Data from square 12 is carried 3 steps, such as: down, left, left.
|
||||
* Data from square 23 is carried only 2 steps: up twice.
|
||||
* Data from square 1024 must be carried 31 steps.
|
||||
|
||||
How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port?
|
||||
|
||||
### Analysis
|
||||
|
||||
I freely admit that I worked out the program I wanted to write using graph paper and some Python doodles. There's no point in trying to write a Joy program until I'm sure I understand the problem well enough.
|
||||
|
||||
The first thing I did was to write a column of numbers from 1 to n (32 as it happens) and next to them the desired output number, to look for patterns directly:
|
||||
|
||||
1 0
|
||||
2 1
|
||||
3 2
|
||||
4 1
|
||||
5 2
|
||||
6 1
|
||||
7 2
|
||||
8 1
|
||||
9 2
|
||||
10 3
|
||||
11 2
|
||||
12 3
|
||||
13 4
|
||||
14 3
|
||||
15 2
|
||||
16 3
|
||||
17 4
|
||||
18 3
|
||||
19 2
|
||||
20 3
|
||||
21 4
|
||||
22 3
|
||||
23 2
|
||||
24 3
|
||||
25 4
|
||||
26 5
|
||||
27 4
|
||||
28 3
|
||||
29 4
|
||||
30 5
|
||||
31 6
|
||||
32 5
|
||||
|
||||
There are four groups repeating for a given "rank", then the pattern enlarges and four groups repeat again, etc.
|
||||
|
||||
1 2
|
||||
3 2 3 4
|
||||
5 4 3 4 5 6
|
||||
7 6 5 4 5 6 7 8
|
||||
9 8 7 6 5 6 7 8 9 10
|
||||
|
||||
Four of this pyramid interlock to tile the plane extending from the initial "1" square.
|
||||
|
||||
|
||||
2 3 | 4 5 | 6 7 | 8 9
|
||||
10 11 12 13|14 15 16 17|18 19 20 21|22 23 24 25
|
||||
|
||||
And so on.
|
||||
|
||||
We can figure out the pattern for a row of the pyramid at a given "rank" $k$:
|
||||
|
||||
$2k - 1, 2k - 2, ..., k, k + 1, k + 2, ..., 2k$
|
||||
|
||||
or
|
||||
|
||||
$k + (k - 1), k + (k - 2), ..., k, k + 1, k + 2, ..., k + k$
|
||||
|
||||
This shows that the series consists at each place of $k$ plus some number that begins at $k - 1$, decreases to zero, then increases to $k$. Each row has $2k$ members.
|
||||
|
||||
Let's figure out how, given an index into a row, we can calculate the value there. The index will be from 0 to $k - 1$.
|
||||
|
||||
Let's look at an example, with $k = 4$:
|
||||
|
||||
0 1 2 3 4 5 6 7
|
||||
7 6 5 4 5 6 7 8
|
||||
|
||||
|
||||
```python
|
||||
k = 4
|
||||
```
|
||||
|
||||
Subtract $k$ from the index and take the absolute value:
|
||||
|
||||
|
||||
```python
|
||||
for n in range(2 * k):
|
||||
print abs(n - k),
|
||||
```
|
||||
|
||||
4 3 2 1 0 1 2 3
|
||||
|
||||
|
||||
Not quite. Subtract $k - 1$ from the index and take the absolute value:
|
||||
|
||||
|
||||
```python
|
||||
for n in range(2 * k):
|
||||
print abs(n - (k - 1)),
|
||||
```
|
||||
|
||||
3 2 1 0 1 2 3 4
|
||||
|
||||
|
||||
Great, now add $k$...
|
||||
|
||||
|
||||
```python
|
||||
for n in range(2 * k):
|
||||
print abs(n - (k - 1)) + k,
|
||||
```
|
||||
|
||||
7 6 5 4 5 6 7 8
|
||||
|
||||
|
||||
So to write a function that can give us the value of a row at a given index:
|
||||
|
||||
|
||||
```python
|
||||
def row_value(k, i):
|
||||
i %= (2 * k) # wrap the index at the row boundary.
|
||||
return abs(i - (k - 1)) + k
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
k = 5
|
||||
for i in range(2 * k):
|
||||
print row_value(k, i),
|
||||
```
|
||||
|
||||
9 8 7 6 5 6 7 8 9 10
|
||||
|
||||
|
||||
(I'm leaving out details of how I figured this all out and just giving the relevent bits. It took a little while to zero in of the aspects of the pattern that were important for the task.)
|
||||
|
||||
### Finding the rank and offset of a number.
|
||||
Now that we can compute the desired output value for a given rank and the offset (index) into that rank, we need to determine how to find the rank and offset of a number.
|
||||
|
||||
The rank is easy to find by iteratively stripping off the amount already covered by previous ranks until you find the one that brackets the target number. Because each row is $2k$ places and there are $4$ per rank each rank contains $8k$ places. Counting the initial square we have:
|
||||
|
||||
$corner_k = 1 + \sum_{n=1}^k 8n$
|
||||
|
||||
I'm not mathematically sophisticated enough to turn this directly into a formula (but Sympy is, see below.) I'm going to write a simple Python function to iterate and search:
|
||||
|
||||
|
||||
```python
|
||||
def rank_and_offset(n):
|
||||
assert n >= 2 # Guard the domain.
|
||||
n -= 2 # Subtract two,
|
||||
# one for the initial square,
|
||||
# and one because we are counting from 1 instead of 0.
|
||||
k = 1
|
||||
while True:
|
||||
m = 8 * k # The number of places total in this rank, 4(2k).
|
||||
if n < m:
|
||||
return k, n % (2 * k)
|
||||
n -= m # Remove this rank's worth.
|
||||
k += 1
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
for n in range(2, 51):
|
||||
print n, rank_and_offset(n)
|
||||
```
|
||||
|
||||
2 (1, 0)
|
||||
3 (1, 1)
|
||||
4 (1, 0)
|
||||
5 (1, 1)
|
||||
6 (1, 0)
|
||||
7 (1, 1)
|
||||
8 (1, 0)
|
||||
9 (1, 1)
|
||||
10 (2, 0)
|
||||
11 (2, 1)
|
||||
12 (2, 2)
|
||||
13 (2, 3)
|
||||
14 (2, 0)
|
||||
15 (2, 1)
|
||||
16 (2, 2)
|
||||
17 (2, 3)
|
||||
18 (2, 0)
|
||||
19 (2, 1)
|
||||
20 (2, 2)
|
||||
21 (2, 3)
|
||||
22 (2, 0)
|
||||
23 (2, 1)
|
||||
24 (2, 2)
|
||||
25 (2, 3)
|
||||
26 (3, 0)
|
||||
27 (3, 1)
|
||||
28 (3, 2)
|
||||
29 (3, 3)
|
||||
30 (3, 4)
|
||||
31 (3, 5)
|
||||
32 (3, 0)
|
||||
33 (3, 1)
|
||||
34 (3, 2)
|
||||
35 (3, 3)
|
||||
36 (3, 4)
|
||||
37 (3, 5)
|
||||
38 (3, 0)
|
||||
39 (3, 1)
|
||||
40 (3, 2)
|
||||
41 (3, 3)
|
||||
42 (3, 4)
|
||||
43 (3, 5)
|
||||
44 (3, 0)
|
||||
45 (3, 1)
|
||||
46 (3, 2)
|
||||
47 (3, 3)
|
||||
48 (3, 4)
|
||||
49 (3, 5)
|
||||
50 (4, 0)
|
||||
|
||||
|
||||
|
||||
```python
|
||||
for n in range(2, 51):
|
||||
k, i = rank_and_offset(n)
|
||||
print n, row_value(k, i)
|
||||
```
|
||||
|
||||
2 1
|
||||
3 2
|
||||
4 1
|
||||
5 2
|
||||
6 1
|
||||
7 2
|
||||
8 1
|
||||
9 2
|
||||
10 3
|
||||
11 2
|
||||
12 3
|
||||
13 4
|
||||
14 3
|
||||
15 2
|
||||
16 3
|
||||
17 4
|
||||
18 3
|
||||
19 2
|
||||
20 3
|
||||
21 4
|
||||
22 3
|
||||
23 2
|
||||
24 3
|
||||
25 4
|
||||
26 5
|
||||
27 4
|
||||
28 3
|
||||
29 4
|
||||
30 5
|
||||
31 6
|
||||
32 5
|
||||
33 4
|
||||
34 3
|
||||
35 4
|
||||
36 5
|
||||
37 6
|
||||
38 5
|
||||
39 4
|
||||
40 3
|
||||
41 4
|
||||
42 5
|
||||
43 6
|
||||
44 5
|
||||
45 4
|
||||
46 3
|
||||
47 4
|
||||
48 5
|
||||
49 6
|
||||
50 7
|
||||
|
||||
|
||||
### Putting it all together
|
||||
|
||||
|
||||
```python
|
||||
def row_value(k, i):
|
||||
return abs(i - (k - 1)) + k
|
||||
|
||||
|
||||
def rank_and_offset(n):
|
||||
n -= 2 # Subtract two,
|
||||
# one for the initial square,
|
||||
# and one because we are counting from 1 instead of 0.
|
||||
k = 1
|
||||
while True:
|
||||
m = 8 * k # The number of places total in this rank, 4(2k).
|
||||
if n < m:
|
||||
return k, n % (2 * k)
|
||||
n -= m # Remove this rank's worth.
|
||||
k += 1
|
||||
|
||||
|
||||
def aoc20173(n):
|
||||
if n <= 1:
|
||||
return 0
|
||||
k, i = rank_and_offset(n)
|
||||
return row_value(k, i)
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
aoc20173(23)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
2
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
aoc20173(23000)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
105
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
aoc20173(23000000000000)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
4572225
|
||||
|
||||
|
||||
|
||||
# Sympy to the Rescue
|
||||
### Find the rank for large numbers
|
||||
Using e.g. Sympy we can find the rank directly by solving for the roots of an equation. For large numbers this will (eventually) be faster than iterating as `rank_and_offset()` does.
|
||||
|
||||
|
||||
```python
|
||||
from sympy import floor, lambdify, solve, symbols
|
||||
from sympy import init_printing
|
||||
init_printing()
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
k = symbols('k')
|
||||
```
|
||||
|
||||
Since
|
||||
|
||||
$1 + 2 + 3 + ... + N = \frac{N(N + 1)}{2}$
|
||||
|
||||
and
|
||||
|
||||
$\sum_{n=1}^k 8n = 8(\sum_{n=1}^k n) = 8\frac{k(k + 1)}{2}$
|
||||
|
||||
We want:
|
||||
|
||||
|
||||
```python
|
||||
E = 2 + 8 * k * (k + 1) / 2 # For the reason for adding 2 see above.
|
||||
|
||||
E
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$4 k \left(k + 1\right) + 2$$
|
||||
|
||||
|
||||
|
||||
We can write a function to solve for $k$ given some $n$...
|
||||
|
||||
|
||||
```python
|
||||
def rank_of(n):
|
||||
return floor(max(solve(E - n, k))) + 1
|
||||
```
|
||||
|
||||
First `solve()` for $E - n = 0$ which has two solutions (because the equation is quadratic so it has two roots) and since we only care about the larger one we use `max()` to select it. It will generally not be a nice integer (unless $n$ is the number of an end-corner of a rank) so we take the `floor()` and add 1 to get the integer rank of $n$. (Taking the `ceiling()` gives off-by-one errors on the rank boundaries. I don't know why. I'm basically like a monkey doing math here.) =-D
|
||||
|
||||
It gives correct answers:
|
||||
|
||||
|
||||
```python
|
||||
for n in (9, 10, 25, 26, 49, 50):
|
||||
print n, rank_of(n)
|
||||
```
|
||||
|
||||
9 1
|
||||
10 2
|
||||
25 2
|
||||
26 3
|
||||
49 3
|
||||
50 4
|
||||
|
||||
|
||||
And it runs much faster (at least for large numbers):
|
||||
|
||||
|
||||
```python
|
||||
%time rank_of(23000000000000) # Compare runtime with rank_and_offset()!
|
||||
```
|
||||
|
||||
CPU times: user 68 ms, sys: 8 ms, total: 76 ms
|
||||
Wall time: 73.8 ms
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$$2397916$$
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
%time rank_and_offset(23000000000000)
|
||||
```
|
||||
|
||||
CPU times: user 308 ms, sys: 0 ns, total: 308 ms
|
||||
Wall time: 306 ms
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$$\left ( 2397916, \quad 223606\right )$$
|
||||
|
||||
|
||||
|
||||
After finding the rank you would still have to find the actual value of the rank's first corner and subtract it (plus 2) from the number and compute the offset as above and then the final output, but this overhead is partially shared by the other method, and overshadowed by the time it (the other iterative method) would take for really big inputs.
|
||||
|
||||
The fun thing to do here would be to graph the actual runtime of both methods against each other to find the trade-off point.
|
||||
|
||||
### It took me a second to realize I could do this...
|
||||
Sympy is a *symbolic* math library, and it supports symbolic manipulation of equations. I can put in $y$ (instead of a value) and ask it to solve for $k$.
|
||||
|
||||
|
||||
```python
|
||||
y = symbols('y')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
g, f = solve(E - y, k)
|
||||
```
|
||||
|
||||
The equation is quadratic so there are two roots, we are interested in the greater one...
|
||||
|
||||
|
||||
```python
|
||||
g
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$- \frac{1}{2} \sqrt{y - 1} - \frac{1}{2}$$
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
f
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$\frac{1}{2} \sqrt{y - 1} - \frac{1}{2}$$
|
||||
|
||||
|
||||
|
||||
Now we can take the `floor()`, add 1, and `lambdify()` the equation to get a Python function that calculates the rank directly.
|
||||
|
||||
|
||||
```python
|
||||
floor(f) + 1
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$\lfloor{\frac{1}{2} \sqrt{y - 1} - \frac{1}{2}}\rfloor + 1$$
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
F = lambdify(y, floor(f) + 1)
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
for n in (9, 10, 25, 26, 49, 50):
|
||||
print n, int(F(n))
|
||||
```
|
||||
|
||||
9 1
|
||||
10 2
|
||||
25 2
|
||||
26 3
|
||||
49 3
|
||||
50 4
|
||||
|
||||
|
||||
It's pretty fast.
|
||||
|
||||
|
||||
```python
|
||||
%time int(F(23000000000000)) # The clear winner.
|
||||
```
|
||||
|
||||
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||
Wall time: 11.9 µs
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$$2397916$$
|
||||
|
||||
|
||||
|
||||
Knowing the equation we could write our own function manually, but the speed is no better.
|
||||
|
||||
|
||||
```python
|
||||
from math import floor as mfloor, sqrt
|
||||
|
||||
def mrank_of(n):
|
||||
return int(mfloor(sqrt(23000000000000 - 1) / 2 - 0.5) + 1)
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
%time mrank_of(23000000000000)
|
||||
```
|
||||
|
||||
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||
Wall time: 12.9 µs
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$$2397916$$
|
||||
|
||||
|
||||
|
||||
### Given $n$ and a rank, compute the offset.
|
||||
|
||||
Now that we have a fast way to get the rank, we still need to use it to compute the offset into a pyramid row.
|
||||
|
||||
|
||||
```python
|
||||
def offset_of(n, k):
|
||||
return (n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||
```
|
||||
|
||||
(Note the sneaky way the sign changes from $k(k + 1)$ to $k(k - 1)$. This is because we want to subract the $(k - 1)$th rank's total places (its own and those of lesser rank) from our $n$ of rank $k$. Substituting $k - 1$ for $k$ in $k(k + 1)$ gives $(k - 1)(k - 1 + 1)$, which of course simplifies to $k(k - 1)$.)
|
||||
|
||||
|
||||
```python
|
||||
offset_of(23000000000000, 2397916)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$223606$$
|
||||
|
||||
|
||||
|
||||
So, we can compute the rank, then the offset, then the row value.
|
||||
|
||||
|
||||
```python
|
||||
def rank_of(n):
|
||||
return int(mfloor(sqrt(n - 1) / 2 - 0.5) + 1)
|
||||
|
||||
|
||||
def offset_of(n, k):
|
||||
return (n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||
|
||||
|
||||
def row_value(k, i):
|
||||
return abs(i - (k - 1)) + k
|
||||
|
||||
|
||||
def aoc20173(n):
|
||||
k = rank_of(n)
|
||||
i = offset_of(n, k)
|
||||
return row_value(k, i)
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
aoc20173(23)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$2$$
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
aoc20173(23000)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$105$$
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
aoc20173(23000000000000)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
$$4572225$$
|
||||
|
||||
|
||||
|
||||
|
||||
```python
|
||||
%time aoc20173(23000000000000000000000000) # Fast for large values.
|
||||
```
|
||||
|
||||
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||
Wall time: 20 µs
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$$2690062495969$$
|
||||
|
||||
|
||||
|
||||
# A Joy Version
|
||||
At this point I feel confident that I can implement a concise version of this code in Joy. ;-)
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import J, V, define
|
||||
```
|
||||
|
||||
### `rank_of`
|
||||
|
||||
n rank_of
|
||||
---------------
|
||||
k
|
||||
|
||||
The translation is straightforward.
|
||||
|
||||
int(floor(sqrt(n - 1) / 2 - 0.5) + 1)
|
||||
|
||||
rank_of == -- sqrt 2 / 0.5 - floor ++
|
||||
|
||||
|
||||
```python
|
||||
define('rank_of == -- sqrt 2 / 0.5 - floor ++')
|
||||
```
|
||||
|
||||
### `offset_of`
|
||||
|
||||
n k offset_of
|
||||
-------------------
|
||||
i
|
||||
|
||||
(n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||
|
||||
A little tricky...
|
||||
|
||||
n k dup 2 *
|
||||
n k k 2 *
|
||||
n k k*2 [Q] dip %
|
||||
n k Q k*2 %
|
||||
|
||||
n k dup --
|
||||
n k k --
|
||||
n k k-1 4 * * 2 + -
|
||||
n k*k-1*4 2 + -
|
||||
n k*k-1*4+2 -
|
||||
n-k*k-1*4+2
|
||||
|
||||
n-k*k-1*4+2 k*2 %
|
||||
n-k*k-1*4+2%k*2
|
||||
|
||||
Ergo:
|
||||
|
||||
offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %
|
||||
|
||||
|
||||
```python
|
||||
define('offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %')
|
||||
```
|
||||
|
||||
### `row_value`
|
||||
|
||||
k i row_value
|
||||
-------------------
|
||||
n
|
||||
|
||||
abs(i - (k - 1)) + k
|
||||
|
||||
k i over -- - abs +
|
||||
k i k -- - abs +
|
||||
k i k-1 - abs +
|
||||
k i-k-1 abs +
|
||||
k |i-k-1| +
|
||||
k+|i-k-1|
|
||||
|
||||
|
||||
```python
|
||||
define('row_value == over -- - abs +')
|
||||
```
|
||||
|
||||
### `aoc2017.3`
|
||||
|
||||
n aoc2017.3
|
||||
-----------------
|
||||
m
|
||||
|
||||
n dup rank_of
|
||||
n k [offset_of] dupdip
|
||||
n k offset_of k
|
||||
i k swap row_value
|
||||
k i row_value
|
||||
m
|
||||
|
||||
|
||||
```python
|
||||
define('aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('23 aoc2017.3')
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('23000 aoc2017.3')
|
||||
```
|
||||
|
||||
105
|
||||
|
||||
|
||||
|
||||
```python
|
||||
V('23000000000000 aoc2017.3')
|
||||
```
|
||||
|
||||
. 23000000000000 aoc2017.3
|
||||
23000000000000 . aoc2017.3
|
||||
23000000000000 . dup rank_of [offset_of] dupdip swap row_value
|
||||
23000000000000 23000000000000 . rank_of [offset_of] dupdip swap row_value
|
||||
23000000000000 23000000000000 . -- sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 22999999999999 . sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 4795831.523312615 . 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 4795831.523312615 2 . / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915.7616563076 . 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915.7616563076 0.5 . - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915.2616563076 . floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915 . ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397916 . [offset_of] dupdip swap row_value
|
||||
23000000000000 2397916 [offset_of] . dupdip swap row_value
|
||||
23000000000000 2397916 . offset_of 2397916 swap row_value
|
||||
23000000000000 2397916 . dup 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 2397916 . 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 2397916 2 . * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 4795832 . [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 4795832 [dup -- 4 * * 2 + -] . dip % 2397916 swap row_value
|
||||
23000000000000 2397916 . dup -- 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 2397916 . -- 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 2397915 . 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 2397915 4 . * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 9591660 . * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 22999994980560 . 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 22999994980560 2 . + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 22999994980562 . - 4795832 % 2397916 swap row_value
|
||||
5019438 . 4795832 % 2397916 swap row_value
|
||||
5019438 4795832 . % 2397916 swap row_value
|
||||
223606 . 2397916 swap row_value
|
||||
223606 2397916 . swap row_value
|
||||
2397916 223606 . row_value
|
||||
2397916 223606 . over -- - abs +
|
||||
2397916 223606 2397916 . -- - abs +
|
||||
2397916 223606 2397915 . - abs +
|
||||
2397916 -2174309 . abs +
|
||||
2397916 2174309 . +
|
||||
4572225 .
|
||||
|
||||
|
||||
rank_of == -- sqrt 2 / 0.5 - floor ++
|
||||
offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %
|
||||
row_value == over -- - abs +
|
||||
|
||||
aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value
|
||||
|
|
@ -1,973 +0,0 @@
|
|||
|
||||
Advent of Code 2017
|
||||
===================
|
||||
|
||||
December 3rd
|
||||
------------
|
||||
|
||||
You come across an experimental new kind of memory stored on an infinite
|
||||
two-dimensional grid.
|
||||
|
||||
Each square on the grid is allocated in a spiral pattern starting at a
|
||||
location marked 1 and then counting up while spiraling outward. For
|
||||
example, the first few squares are allocated like this:
|
||||
|
||||
::
|
||||
|
||||
17 16 15 14 13
|
||||
18 5 4 3 12
|
||||
19 6 1 2 11
|
||||
20 7 8 9 10
|
||||
21 22 23---> ...
|
||||
|
||||
While this is very space-efficient (no squares are skipped), requested
|
||||
data must be carried back to square 1 (the location of the only access
|
||||
port for this memory system) by programs that can only move up, down,
|
||||
left, or right. They always take the shortest path: the Manhattan
|
||||
Distance between the location of the data and square 1.
|
||||
|
||||
For example:
|
||||
|
||||
- Data from square 1 is carried 0 steps, since it's at the access port.
|
||||
- Data from square 12 is carried 3 steps, such as: down, left, left.
|
||||
- Data from square 23 is carried only 2 steps: up twice.
|
||||
- Data from square 1024 must be carried 31 steps.
|
||||
|
||||
How many steps are required to carry the data from the square identified
|
||||
in your puzzle input all the way to the access port?
|
||||
|
||||
Analysis
|
||||
~~~~~~~~
|
||||
|
||||
I freely admit that I worked out the program I wanted to write using
|
||||
graph paper and some Python doodles. There's no point in trying to write
|
||||
a Joy program until I'm sure I understand the problem well enough.
|
||||
|
||||
The first thing I did was to write a column of numbers from 1 to n (32
|
||||
as it happens) and next to them the desired output number, to look for
|
||||
patterns directly:
|
||||
|
||||
::
|
||||
|
||||
1 0
|
||||
2 1
|
||||
3 2
|
||||
4 1
|
||||
5 2
|
||||
6 1
|
||||
7 2
|
||||
8 1
|
||||
9 2
|
||||
10 3
|
||||
11 2
|
||||
12 3
|
||||
13 4
|
||||
14 3
|
||||
15 2
|
||||
16 3
|
||||
17 4
|
||||
18 3
|
||||
19 2
|
||||
20 3
|
||||
21 4
|
||||
22 3
|
||||
23 2
|
||||
24 3
|
||||
25 4
|
||||
26 5
|
||||
27 4
|
||||
28 3
|
||||
29 4
|
||||
30 5
|
||||
31 6
|
||||
32 5
|
||||
|
||||
There are four groups repeating for a given "rank", then the pattern
|
||||
enlarges and four groups repeat again, etc.
|
||||
|
||||
::
|
||||
|
||||
1 2
|
||||
3 2 3 4
|
||||
5 4 3 4 5 6
|
||||
7 6 5 4 5 6 7 8
|
||||
9 8 7 6 5 6 7 8 9 10
|
||||
|
||||
Four of this pyramid interlock to tile the plane extending from the
|
||||
initial "1" square.
|
||||
|
||||
::
|
||||
|
||||
2 3 | 4 5 | 6 7 | 8 9
|
||||
10 11 12 13|14 15 16 17|18 19 20 21|22 23 24 25
|
||||
|
||||
And so on.
|
||||
|
||||
We can figure out the pattern for a row of the pyramid at a given "rank"
|
||||
:math:`k`:
|
||||
|
||||
:math:`2k - 1, 2k - 2, ..., k, k + 1, k + 2, ..., 2k`
|
||||
|
||||
or
|
||||
|
||||
:math:`k + (k - 1), k + (k - 2), ..., k, k + 1, k + 2, ..., k + k`
|
||||
|
||||
This shows that the series consists at each place of :math:`k` plus some
|
||||
number that begins at :math:`k - 1`, decreases to zero, then increases
|
||||
to :math:`k`. Each row has :math:`2k` members.
|
||||
|
||||
Let's figure out how, given an index into a row, we can calculate the
|
||||
value there. The index will be from 0 to :math:`k - 1`.
|
||||
|
||||
Let's look at an example, with :math:`k = 4`:
|
||||
|
||||
::
|
||||
|
||||
0 1 2 3 4 5 6 7
|
||||
7 6 5 4 5 6 7 8
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
k = 4
|
||||
|
||||
Subtract :math:`k` from the index and take the absolute value:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
for n in range(2 * k):
|
||||
print abs(n - k),
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
4 3 2 1 0 1 2 3
|
||||
|
||||
|
||||
Not quite. Subtract :math:`k - 1` from the index and take the absolute
|
||||
value:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
for n in range(2 * k):
|
||||
print abs(n - (k - 1)),
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3 2 1 0 1 2 3 4
|
||||
|
||||
|
||||
Great, now add :math:`k`...
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
for n in range(2 * k):
|
||||
print abs(n - (k - 1)) + k,
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
7 6 5 4 5 6 7 8
|
||||
|
||||
|
||||
So to write a function that can give us the value of a row at a given
|
||||
index:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
def row_value(k, i):
|
||||
i %= (2 * k) # wrap the index at the row boundary.
|
||||
return abs(i - (k - 1)) + k
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
k = 5
|
||||
for i in range(2 * k):
|
||||
print row_value(k, i),
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
9 8 7 6 5 6 7 8 9 10
|
||||
|
||||
|
||||
(I'm leaving out details of how I figured this all out and just giving
|
||||
the relevent bits. It took a little while to zero in of the aspects of
|
||||
the pattern that were important for the task.)
|
||||
|
||||
Finding the rank and offset of a number.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now that we can compute the desired output value for a given rank and
|
||||
the offset (index) into that rank, we need to determine how to find the
|
||||
rank and offset of a number.
|
||||
|
||||
The rank is easy to find by iteratively stripping off the amount already
|
||||
covered by previous ranks until you find the one that brackets the
|
||||
target number. Because each row is :math:`2k` places and there are
|
||||
:math:`4` per rank each rank contains :math:`8k` places. Counting the
|
||||
initial square we have:
|
||||
|
||||
:math:`corner_k = 1 + \sum_{n=1}^k 8n`
|
||||
|
||||
I'm not mathematically sophisticated enough to turn this directly into a
|
||||
formula (but Sympy is, see below.) I'm going to write a simple Python
|
||||
function to iterate and search:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
def rank_and_offset(n):
|
||||
assert n >= 2 # Guard the domain.
|
||||
n -= 2 # Subtract two,
|
||||
# one for the initial square,
|
||||
# and one because we are counting from 1 instead of 0.
|
||||
k = 1
|
||||
while True:
|
||||
m = 8 * k # The number of places total in this rank, 4(2k).
|
||||
if n < m:
|
||||
return k, n % (2 * k)
|
||||
n -= m # Remove this rank's worth.
|
||||
k += 1
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
for n in range(2, 51):
|
||||
print n, rank_and_offset(n)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2 (1, 0)
|
||||
3 (1, 1)
|
||||
4 (1, 0)
|
||||
5 (1, 1)
|
||||
6 (1, 0)
|
||||
7 (1, 1)
|
||||
8 (1, 0)
|
||||
9 (1, 1)
|
||||
10 (2, 0)
|
||||
11 (2, 1)
|
||||
12 (2, 2)
|
||||
13 (2, 3)
|
||||
14 (2, 0)
|
||||
15 (2, 1)
|
||||
16 (2, 2)
|
||||
17 (2, 3)
|
||||
18 (2, 0)
|
||||
19 (2, 1)
|
||||
20 (2, 2)
|
||||
21 (2, 3)
|
||||
22 (2, 0)
|
||||
23 (2, 1)
|
||||
24 (2, 2)
|
||||
25 (2, 3)
|
||||
26 (3, 0)
|
||||
27 (3, 1)
|
||||
28 (3, 2)
|
||||
29 (3, 3)
|
||||
30 (3, 4)
|
||||
31 (3, 5)
|
||||
32 (3, 0)
|
||||
33 (3, 1)
|
||||
34 (3, 2)
|
||||
35 (3, 3)
|
||||
36 (3, 4)
|
||||
37 (3, 5)
|
||||
38 (3, 0)
|
||||
39 (3, 1)
|
||||
40 (3, 2)
|
||||
41 (3, 3)
|
||||
42 (3, 4)
|
||||
43 (3, 5)
|
||||
44 (3, 0)
|
||||
45 (3, 1)
|
||||
46 (3, 2)
|
||||
47 (3, 3)
|
||||
48 (3, 4)
|
||||
49 (3, 5)
|
||||
50 (4, 0)
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
for n in range(2, 51):
|
||||
k, i = rank_and_offset(n)
|
||||
print n, row_value(k, i)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2 1
|
||||
3 2
|
||||
4 1
|
||||
5 2
|
||||
6 1
|
||||
7 2
|
||||
8 1
|
||||
9 2
|
||||
10 3
|
||||
11 2
|
||||
12 3
|
||||
13 4
|
||||
14 3
|
||||
15 2
|
||||
16 3
|
||||
17 4
|
||||
18 3
|
||||
19 2
|
||||
20 3
|
||||
21 4
|
||||
22 3
|
||||
23 2
|
||||
24 3
|
||||
25 4
|
||||
26 5
|
||||
27 4
|
||||
28 3
|
||||
29 4
|
||||
30 5
|
||||
31 6
|
||||
32 5
|
||||
33 4
|
||||
34 3
|
||||
35 4
|
||||
36 5
|
||||
37 6
|
||||
38 5
|
||||
39 4
|
||||
40 3
|
||||
41 4
|
||||
42 5
|
||||
43 6
|
||||
44 5
|
||||
45 4
|
||||
46 3
|
||||
47 4
|
||||
48 5
|
||||
49 6
|
||||
50 7
|
||||
|
||||
|
||||
Putting it all together
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
def row_value(k, i):
|
||||
return abs(i - (k - 1)) + k
|
||||
|
||||
|
||||
def rank_and_offset(n):
|
||||
n -= 2 # Subtract two,
|
||||
# one for the initial square,
|
||||
# and one because we are counting from 1 instead of 0.
|
||||
k = 1
|
||||
while True:
|
||||
m = 8 * k # The number of places total in this rank, 4(2k).
|
||||
if n < m:
|
||||
return k, n % (2 * k)
|
||||
n -= m # Remove this rank's worth.
|
||||
k += 1
|
||||
|
||||
|
||||
def aoc20173(n):
|
||||
if n <= 1:
|
||||
return 0
|
||||
k, i = rank_and_offset(n)
|
||||
return row_value(k, i)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
aoc20173(23)
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
aoc20173(23000)
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
105
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
aoc20173(23000000000000)
|
||||
|
||||
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
4572225
|
||||
|
||||
|
||||
|
||||
Sympy to the Rescue
|
||||
===================
|
||||
|
||||
Find the rank for large numbers
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Using e.g. Sympy we can find the rank directly by solving for the roots
|
||||
of an equation. For large numbers this will (eventually) be faster than
|
||||
iterating as ``rank_and_offset()`` does.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from sympy import floor, lambdify, solve, symbols
|
||||
from sympy import init_printing
|
||||
init_printing()
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
k = symbols('k')
|
||||
|
||||
Since
|
||||
|
||||
:math:`1 + 2 + 3 + ... + N = \frac{N(N + 1)}{2}`
|
||||
|
||||
and
|
||||
|
||||
:math:`\sum_{n=1}^k 8n = 8(\sum_{n=1}^k n) = 8\frac{k(k + 1)}{2}`
|
||||
|
||||
We want:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
E = 2 + 8 * k * (k + 1) / 2 # For the reason for adding 2 see above.
|
||||
|
||||
E
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
4 k \left(k + 1\right) + 2
|
||||
|
||||
|
||||
|
||||
We can write a function to solve for :math:`k` given some :math:`n`...
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
def rank_of(n):
|
||||
return floor(max(solve(E - n, k))) + 1
|
||||
|
||||
First ``solve()`` for :math:`E - n = 0` which has two solutions (because
|
||||
the equation is quadratic so it has two roots) and since we only care
|
||||
about the larger one we use ``max()`` to select it. It will generally
|
||||
not be a nice integer (unless :math:`n` is the number of an end-corner
|
||||
of a rank) so we take the ``floor()`` and add 1 to get the integer rank
|
||||
of :math:`n`. (Taking the ``ceiling()`` gives off-by-one errors on the
|
||||
rank boundaries. I don't know why. I'm basically like a monkey doing
|
||||
math here.) =-D
|
||||
|
||||
It gives correct answers:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
for n in (9, 10, 25, 26, 49, 50):
|
||||
print n, rank_of(n)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
9 1
|
||||
10 2
|
||||
25 2
|
||||
26 3
|
||||
49 3
|
||||
50 4
|
||||
|
||||
|
||||
And it runs much faster (at least for large numbers):
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
%time rank_of(23000000000000) # Compare runtime with rank_and_offset()!
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
CPU times: user 68 ms, sys: 8 ms, total: 76 ms
|
||||
Wall time: 73.8 ms
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
2397916
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
%time rank_and_offset(23000000000000)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
CPU times: user 308 ms, sys: 0 ns, total: 308 ms
|
||||
Wall time: 306 ms
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
\left ( 2397916, \quad 223606\right )
|
||||
|
||||
|
||||
|
||||
After finding the rank you would still have to find the actual value of
|
||||
the rank's first corner and subtract it (plus 2) from the number and
|
||||
compute the offset as above and then the final output, but this overhead
|
||||
is partially shared by the other method, and overshadowed by the time it
|
||||
(the other iterative method) would take for really big inputs.
|
||||
|
||||
The fun thing to do here would be to graph the actual runtime of both
|
||||
methods against each other to find the trade-off point.
|
||||
|
||||
It took me a second to realize I could do this...
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Sympy is a *symbolic* math library, and it supports symbolic
|
||||
manipulation of equations. I can put in :math:`y` (instead of a value)
|
||||
and ask it to solve for :math:`k`.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
y = symbols('y')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
g, f = solve(E - y, k)
|
||||
|
||||
The equation is quadratic so there are two roots, we are interested in
|
||||
the greater one...
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
g
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
- \frac{1}{2} \sqrt{y - 1} - \frac{1}{2}
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
f
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
\frac{1}{2} \sqrt{y - 1} - \frac{1}{2}
|
||||
|
||||
|
||||
|
||||
Now we can take the ``floor()``, add 1, and ``lambdify()`` the equation
|
||||
to get a Python function that calculates the rank directly.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
floor(f) + 1
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
\lfloor{\frac{1}{2} \sqrt{y - 1} - \frac{1}{2}}\rfloor + 1
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
F = lambdify(y, floor(f) + 1)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
for n in (9, 10, 25, 26, 49, 50):
|
||||
print n, int(F(n))
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
9 1
|
||||
10 2
|
||||
25 2
|
||||
26 3
|
||||
49 3
|
||||
50 4
|
||||
|
||||
|
||||
It's pretty fast.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
%time int(F(23000000000000)) # The clear winner.
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||
Wall time: 11.9 µs
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
2397916
|
||||
|
||||
|
||||
|
||||
Knowing the equation we could write our own function manually, but the
|
||||
speed is no better.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from math import floor as mfloor, sqrt
|
||||
|
||||
def mrank_of(n):
|
||||
return int(mfloor(sqrt(23000000000000 - 1) / 2 - 0.5) + 1)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
%time mrank_of(23000000000000)
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||
Wall time: 12.9 µs
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
2397916
|
||||
|
||||
|
||||
|
||||
Given :math:`n` and a rank, compute the offset.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Now that we have a fast way to get the rank, we still need to use it to
|
||||
compute the offset into a pyramid row.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
def offset_of(n, k):
|
||||
return (n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||
|
||||
(Note the sneaky way the sign changes from :math:`k(k + 1)` to
|
||||
:math:`k(k - 1)`. This is because we want to subract the
|
||||
:math:`(k - 1)`\ th rank's total places (its own and those of lesser
|
||||
rank) from our :math:`n` of rank :math:`k`. Substituting :math:`k - 1`
|
||||
for :math:`k` in :math:`k(k + 1)` gives :math:`(k - 1)(k - 1 + 1)`,
|
||||
which of course simplifies to :math:`k(k - 1)`.)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
offset_of(23000000000000, 2397916)
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
223606
|
||||
|
||||
|
||||
|
||||
So, we can compute the rank, then the offset, then the row value.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
def rank_of(n):
|
||||
return int(mfloor(sqrt(n - 1) / 2 - 0.5) + 1)
|
||||
|
||||
|
||||
def offset_of(n, k):
|
||||
return (n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||
|
||||
|
||||
def row_value(k, i):
|
||||
return abs(i - (k - 1)) + k
|
||||
|
||||
|
||||
def aoc20173(n):
|
||||
k = rank_of(n)
|
||||
i = offset_of(n, k)
|
||||
return row_value(k, i)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
aoc20173(23)
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
2
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
aoc20173(23000)
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
105
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
aoc20173(23000000000000)
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
4572225
|
||||
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
%time aoc20173(23000000000000000000000000) # Fast for large values.
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||
Wall time: 20 µs
|
||||
|
||||
|
||||
|
||||
|
||||
.. math::
|
||||
|
||||
2690062495969
|
||||
|
||||
|
||||
|
||||
A Joy Version
|
||||
=============
|
||||
|
||||
At this point I feel confident that I can implement a concise version of
|
||||
this code in Joy. ;-)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import J, V, define
|
||||
|
||||
``rank_of``
|
||||
~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
n rank_of
|
||||
---------------
|
||||
k
|
||||
|
||||
The translation is straightforward.
|
||||
|
||||
::
|
||||
|
||||
int(floor(sqrt(n - 1) / 2 - 0.5) + 1)
|
||||
|
||||
rank_of == -- sqrt 2 / 0.5 - floor ++
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('rank_of == -- sqrt 2 / 0.5 - floor ++')
|
||||
|
||||
``offset_of``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
n k offset_of
|
||||
-------------------
|
||||
i
|
||||
|
||||
(n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||
|
||||
A little tricky...
|
||||
|
||||
::
|
||||
|
||||
n k dup 2 *
|
||||
n k k 2 *
|
||||
n k k*2 [Q] dip %
|
||||
n k Q k*2 %
|
||||
|
||||
n k dup --
|
||||
n k k --
|
||||
n k k-1 4 * * 2 + -
|
||||
n k*k-1*4 2 + -
|
||||
n k*k-1*4+2 -
|
||||
n-k*k-1*4+2
|
||||
|
||||
n-k*k-1*4+2 k*2 %
|
||||
n-k*k-1*4+2%k*2
|
||||
|
||||
Ergo:
|
||||
|
||||
::
|
||||
|
||||
offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %')
|
||||
|
||||
``row_value``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
k i row_value
|
||||
-------------------
|
||||
n
|
||||
|
||||
abs(i - (k - 1)) + k
|
||||
|
||||
k i over -- - abs +
|
||||
k i k -- - abs +
|
||||
k i k-1 - abs +
|
||||
k i-k-1 abs +
|
||||
k |i-k-1| +
|
||||
k+|i-k-1|
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('row_value == over -- - abs +')
|
||||
|
||||
``aoc2017.3``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
n aoc2017.3
|
||||
-----------------
|
||||
m
|
||||
|
||||
n dup rank_of
|
||||
n k [offset_of] dupdip
|
||||
n k offset_of k
|
||||
i k swap row_value
|
||||
k i row_value
|
||||
m
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('23 aoc2017.3')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('23000 aoc2017.3')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
105
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('23000000000000 aoc2017.3')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 23000000000000 aoc2017.3
|
||||
23000000000000 . aoc2017.3
|
||||
23000000000000 . dup rank_of [offset_of] dupdip swap row_value
|
||||
23000000000000 23000000000000 . rank_of [offset_of] dupdip swap row_value
|
||||
23000000000000 23000000000000 . -- sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 22999999999999 . sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 4795831.523312615 . 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 4795831.523312615 2 . / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915.7616563076 . 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915.7616563076 0.5 . - floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915.2616563076 . floor ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397915 . ++ [offset_of] dupdip swap row_value
|
||||
23000000000000 2397916 . [offset_of] dupdip swap row_value
|
||||
23000000000000 2397916 [offset_of] . dupdip swap row_value
|
||||
23000000000000 2397916 . offset_of 2397916 swap row_value
|
||||
23000000000000 2397916 . dup 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 2397916 . 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 2397916 2 . * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 4795832 . [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||
23000000000000 2397916 4795832 [dup -- 4 * * 2 + -] . dip % 2397916 swap row_value
|
||||
23000000000000 2397916 . dup -- 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 2397916 . -- 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 2397915 . 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 2397915 4 . * * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 2397916 9591660 . * 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 22999994980560 . 2 + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 22999994980560 2 . + - 4795832 % 2397916 swap row_value
|
||||
23000000000000 22999994980562 . - 4795832 % 2397916 swap row_value
|
||||
5019438 . 4795832 % 2397916 swap row_value
|
||||
5019438 4795832 . % 2397916 swap row_value
|
||||
223606 . 2397916 swap row_value
|
||||
223606 2397916 . swap row_value
|
||||
2397916 223606 . row_value
|
||||
2397916 223606 . over -- - abs +
|
||||
2397916 223606 2397916 . -- - abs +
|
||||
2397916 223606 2397915 . - abs +
|
||||
2397916 -2174309 . abs +
|
||||
2397916 2174309 . +
|
||||
4572225 .
|
||||
|
||||
|
||||
::
|
||||
|
||||
rank_of == -- sqrt 2 / 0.5 - floor ++
|
||||
offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %
|
||||
row_value == over -- - abs +
|
||||
|
||||
aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value
|
||||
|
Before Width: | Height: | Size: 677 B |
|
Before Width: | Height: | Size: 566 B |
|
Before Width: | Height: | Size: 977 B |
|
Before Width: | Height: | Size: 655 B |
|
Before Width: | Height: | Size: 665 B |
|
Before Width: | Height: | Size: 758 B |
|
Before Width: | Height: | Size: 566 B |
|
Before Width: | Height: | Size: 566 B |
|
Before Width: | Height: | Size: 453 B |
|
Before Width: | Height: | Size: 239 B |
|
Before Width: | Height: | Size: 337 B |
|
Before Width: | Height: | Size: 447 B |
|
Before Width: | Height: | Size: 784 B |
|
|
@ -1,139 +0,0 @@
|
|||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Advent of Code 2017\n",
|
||||
"\n",
|
||||
"## December 4th\n",
|
||||
"To ensure security, a valid passphrase must contain no duplicate words.\n",
|
||||
"\n",
|
||||
"For example:\n",
|
||||
"\n",
|
||||
"* aa bb cc dd ee is valid.\n",
|
||||
"* aa bb cc dd aa is not valid - the word aa appears more than once.\n",
|
||||
"* aa bb cc dd aaa is valid - aa and aaa count as different words.\n",
|
||||
"\n",
|
||||
"The system's full passphrase list is available as your puzzle input. How many passphrases are valid?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from notebook_preamble import J, V, define"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"I'll assume the input is a Joy sequence of sequences of integers.\n",
|
||||
"\n",
|
||||
" [[5 1 9 5]\n",
|
||||
" [7 5 4 3]\n",
|
||||
" [2 4 6 8]]\n",
|
||||
"\n",
|
||||
"So, obviously, the initial form will be a `step` function:\n",
|
||||
"\n",
|
||||
" AoC2017.4 == 0 swap [F +] step"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
" F == [size] [unique size] cleave =\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The `step_zero` combinator includes the `0 swap` that would normally open one of these definitions:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"0 roll> step\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[step_zero] help')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
" AoC2017.4 == [F +] step_zero"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('AoC2017.4 == [[size] [unique size] cleave = +] step_zero')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"2\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('''\n",
|
||||
"\n",
|
||||
"[[5 1 9 5]\n",
|
||||
" [7 5 4 3]\n",
|
||||
" [2 4 6 8]] AoC2017.4\n",
|
||||
"\n",
|
||||
"''')"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
|
||||
# Advent of Code 2017
|
||||
|
||||
## December 4th
|
||||
To ensure security, a valid passphrase must contain no duplicate words.
|
||||
|
||||
For example:
|
||||
|
||||
* aa bb cc dd ee is valid.
|
||||
* aa bb cc dd aa is not valid - the word aa appears more than once.
|
||||
* aa bb cc dd aaa is valid - aa and aaa count as different words.
|
||||
|
||||
The system's full passphrase list is available as your puzzle input. How many passphrases are valid?
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import J, V, define
|
||||
```
|
||||
|
||||
I'll assume the input is a Joy sequence of sequences of integers.
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 4 3]
|
||||
[2 4 6 8]]
|
||||
|
||||
So, obviously, the initial form will be a `step` function:
|
||||
|
||||
AoC2017.4 == 0 swap [F +] step
|
||||
|
||||
|
||||
F == [size] [unique size] cleave =
|
||||
|
||||
|
||||
The `step_zero` combinator includes the `0 swap` that would normally open one of these definitions:
|
||||
|
||||
|
||||
```python
|
||||
J('[step_zero] help')
|
||||
```
|
||||
|
||||
0 roll> step
|
||||
|
||||
|
||||
|
||||
AoC2017.4 == [F +] step_zero
|
||||
|
||||
|
||||
```python
|
||||
define('AoC2017.4 == [[size] [unique size] cleave = +] step_zero')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('''
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 4 3]
|
||||
[2 4 6 8]] AoC2017.4
|
||||
|
||||
''')
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
|
||||
Advent of Code 2017
|
||||
===================
|
||||
|
||||
December 4th
|
||||
------------
|
||||
|
||||
To ensure security, a valid passphrase must contain no duplicate words.
|
||||
|
||||
For example:
|
||||
|
||||
- aa bb cc dd ee is valid.
|
||||
- aa bb cc dd aa is not valid - the word aa appears more than once.
|
||||
- aa bb cc dd aaa is valid - aa and aaa count as different words.
|
||||
|
||||
The system's full passphrase list is available as your puzzle input. How
|
||||
many passphrases are valid?
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import J, V, define
|
||||
|
||||
I'll assume the input is a Joy sequence of sequences of integers.
|
||||
|
||||
::
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 4 3]
|
||||
[2 4 6 8]]
|
||||
|
||||
So, obviously, the initial form will be a ``step`` function:
|
||||
|
||||
::
|
||||
|
||||
AoC2017.4 == 0 swap [F +] step
|
||||
|
||||
::
|
||||
|
||||
F == [size] [unique size] cleave =
|
||||
|
||||
The ``step_zero`` combinator includes the ``0 swap`` that would normally
|
||||
open one of these definitions:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[step_zero] help')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
0 roll> step
|
||||
|
||||
|
||||
|
||||
::
|
||||
|
||||
AoC2017.4 == [F +] step_zero
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('AoC2017.4 == [[size] [unique size] cleave = +] step_zero')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('''
|
||||
|
||||
[[5 1 9 5]
|
||||
[7 5 4 3]
|
||||
[2 4 6 8]] AoC2017.4
|
||||
|
||||
''')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2
|
||||
|
||||
|
|
@ -1,380 +0,0 @@
|
|||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Advent of Code 2017\n",
|
||||
"\n",
|
||||
"## December 5th\n",
|
||||
"...a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list.\n",
|
||||
"\n",
|
||||
"In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered.\n",
|
||||
"\n",
|
||||
"For example, consider the following list of jump offsets:\n",
|
||||
"\n",
|
||||
" 0\n",
|
||||
" 3\n",
|
||||
" 0\n",
|
||||
" 1\n",
|
||||
" -3\n",
|
||||
"\n",
|
||||
"Positive jumps (\"forward\") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found:\n",
|
||||
"\n",
|
||||
"* (0) 3 0 1 -3 - before we have taken any steps.\n",
|
||||
"* (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.\n",
|
||||
"* 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.\n",
|
||||
"* 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind.\n",
|
||||
"* 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2.\n",
|
||||
"* 2 5 0 1 -2 - jump 4 steps forward, escaping the maze.\n",
|
||||
"\n",
|
||||
"In this example, the exit is reached in 5 steps.\n",
|
||||
"\n",
|
||||
"How many steps does it take to reach the exit?"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Breakdown\n",
|
||||
"For now, I'm going to assume a starting state with the size of the sequence pre-computed. We need it to define the exit condition and it is a trivial preamble to generate it. We then need and `index` and a `step-count`, which are both initially zero. Then we have the sequence itself, and some recursive function `F` that does the work.\n",
|
||||
"\n",
|
||||
" size index step-count [...] F\n",
|
||||
" -----------------------------------\n",
|
||||
" step-count\n",
|
||||
"\n",
|
||||
" F == [P] [T] [R1] [R2] genrec\n",
|
||||
"\n",
|
||||
"Later on I was thinking about it and the Forth heuristic came to mind, to wit: four things on the stack are kind of much. Immediately I realized that the size properly belongs in the predicate of `F`! D'oh!\n",
|
||||
"\n",
|
||||
" index step-count [...] F\n",
|
||||
" ------------------------------\n",
|
||||
" step-count"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"So, let's start by nailing down the predicate:\n",
|
||||
"\n",
|
||||
" F == [P] [T] [R1] [R2] genrec\n",
|
||||
" == [P] [T] [R1 [F] R2] ifte\n",
|
||||
"\n",
|
||||
" 0 0 [0 3 0 1 -3] popop 5 >=\n",
|
||||
"\n",
|
||||
" P == popop 5 >="
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we need the else-part:\n",
|
||||
"\n",
|
||||
" index step-count [0 3 0 1 -3] roll< popop\n",
|
||||
"\n",
|
||||
" E == roll< popop"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Last but not least, the recursive branch\n",
|
||||
"\n",
|
||||
" 0 0 [0 3 0 1 -3] R1 [F] R2\n",
|
||||
"\n",
|
||||
"The `R1` function has a big job:\n",
|
||||
"\n",
|
||||
" R1 == get the value at index\n",
|
||||
" increment the value at the index\n",
|
||||
" add the value gotten to the index\n",
|
||||
" increment the step count\n",
|
||||
"\n",
|
||||
"The only tricky thing there is incrementing an integer in the sequence. Joy sequences are not particularly good for random access. We could encode the list of jump offsets in a big integer and use math to do the processing for a good speed-up, but it still wouldn't beat the performance of e.g. a mutable array. This is just one of those places where \"plain vanilla\" Joypy doesn't shine (in default performance. The legendary *Sufficiently-Smart Compiler* would of course rewrite this function to use an array \"under the hood\".)\n",
|
||||
"\n",
|
||||
"In the meantime, I'm going to write a primitive function that just does what we need."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from notebook_preamble import D, J, V, define\n",
|
||||
"from joy.library import SimpleFunctionWrapper\n",
|
||||
"from joy.utils.stack import list_to_stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@SimpleFunctionWrapper\n",
|
||||
"def incr_at(stack):\n",
|
||||
" '''Given a index and a sequence of integers, increment the integer at the index.\n",
|
||||
"\n",
|
||||
" E.g.:\n",
|
||||
"\n",
|
||||
" 3 [0 1 2 3 4 5] incr_at\n",
|
||||
" -----------------------------\n",
|
||||
" [0 1 2 4 4 5]\n",
|
||||
" \n",
|
||||
" '''\n",
|
||||
" sequence, (i, stack) = stack\n",
|
||||
" mem = []\n",
|
||||
" while i >= 0:\n",
|
||||
" term, sequence = sequence\n",
|
||||
" mem.append(term)\n",
|
||||
" i -= 1\n",
|
||||
" mem[-1] += 1\n",
|
||||
" return list_to_stack(mem, sequence), stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"D['incr_at'] = incr_at"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[0 1 2 4 4 5]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('3 [0 1 2 3 4 5] incr_at')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### get the value at index\n",
|
||||
"\n",
|
||||
" 3 0 [0 1 2 3 4] [roll< at] nullary\n",
|
||||
" 3 0 [0 1 2 n 4] n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### increment the value at the index\n",
|
||||
"\n",
|
||||
" 3 0 [0 1 2 n 4] n [Q] dip\n",
|
||||
" 3 0 [0 1 2 n 4] Q n\n",
|
||||
" 3 0 [0 1 2 n 4] [popd incr_at] unary n\n",
|
||||
" 3 0 [0 1 2 n+1 4] n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### add the value gotten to the index\n",
|
||||
"\n",
|
||||
" 3 0 [0 1 2 n+1 4] n [+] cons dipd\n",
|
||||
" 3 0 [0 1 2 n+1 4] [n +] dipd\n",
|
||||
" 3 n + 0 [0 1 2 n+1 4]\n",
|
||||
" 3+n 0 [0 1 2 n+1 4]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### increment the step count\n",
|
||||
"\n",
|
||||
" 3+n 0 [0 1 2 n+1 4] [++] dip\n",
|
||||
" 3+n 1 [0 1 2 n+1 4]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### All together now...\n",
|
||||
"\n",
|
||||
" get_value == [roll< at] nullary\n",
|
||||
" incr_value == [[popd incr_at] unary] dip\n",
|
||||
" add_value == [+] cons dipd\n",
|
||||
" incr_step_count == [++] dip\n",
|
||||
"\n",
|
||||
" R1 == get_value incr_value add_value incr_step_count\n",
|
||||
"\n",
|
||||
" F == [P] [T] [R1] primrec\n",
|
||||
" \n",
|
||||
" F == [popop !size! >=] [roll< pop] [get_value incr_value add_value incr_step_count] primrec"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from joy.library import DefinitionWrapper\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"DefinitionWrapper.add_definitions('''\n",
|
||||
"\n",
|
||||
" get_value == [roll< at] nullary\n",
|
||||
" incr_value == [[popd incr_at] unary] dip\n",
|
||||
" add_value == [+] cons dipd\n",
|
||||
"incr_step_count == [++] dip\n",
|
||||
"\n",
|
||||
" AoC2017.5.0 == get_value incr_value add_value incr_step_count\n",
|
||||
"\n",
|
||||
"''', D)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('F == [popop 5 >=] [roll< popop] [AoC2017.5.0] primrec')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"5\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('0 0 [0 3 0 1 -3] F')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Preamble for setting up predicate, `index`, and `step-count`\n",
|
||||
"\n",
|
||||
"We want to go from this to this:\n",
|
||||
"\n",
|
||||
" [...] AoC2017.5.preamble\n",
|
||||
" ------------------------------\n",
|
||||
" 0 0 [...] [popop n >=]\n",
|
||||
"\n",
|
||||
"Where `n` is the size of the sequence.\n",
|
||||
"\n",
|
||||
"The first part is obviously `0 0 roll<`, then `dup size`:\n",
|
||||
"\n",
|
||||
" [...] 0 0 roll< dup size\n",
|
||||
" 0 0 [...] n\n",
|
||||
"\n",
|
||||
"Then:\n",
|
||||
"\n",
|
||||
" 0 0 [...] n [>=] cons [popop] swoncat\n",
|
||||
"\n",
|
||||
"So:\n",
|
||||
"\n",
|
||||
" init-index-and-step-count == 0 0 roll<\n",
|
||||
" prepare-predicate == dup size [>=] cons [popop] swoncat\n",
|
||||
"\n",
|
||||
" AoC2017.5.preamble == init-index-and-step-count prepare-predicate"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"DefinitionWrapper.add_definitions('''\n",
|
||||
"\n",
|
||||
"init-index-and-step-count == 0 0 roll<\n",
|
||||
" prepare-predicate == dup size [>=] cons [popop] swoncat\n",
|
||||
"\n",
|
||||
" AoC2017.5.preamble == init-index-and-step-count prepare-predicate\n",
|
||||
"\n",
|
||||
" AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec\n",
|
||||
"\n",
|
||||
"''', D)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"5\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 3 0 1 -3] AoC2017.5')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
" AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec\n",
|
||||
"\n",
|
||||
" AoC2017.5.0 == get_value incr_value add_value incr_step_count\n",
|
||||
" AoC2017.5.preamble == init-index-and-step-count prepare-predicate\n",
|
||||
"\n",
|
||||
" get_value == [roll< at] nullary\n",
|
||||
" incr_value == [[popd incr_at] unary] dip\n",
|
||||
" add_value == [+] cons dipd\n",
|
||||
" incr_step_count == [++] dip\n",
|
||||
"\n",
|
||||
" init-index-and-step-count == 0 0 roll<\n",
|
||||
" prepare-predicate == dup size [>=] cons [popop] swoncat\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This is by far the largest program I have yet written in Joy. Even with the `incr_at` function it is still a bear. There may be an arrangement of the parameters that would permit more elegant definitions, but it still wouldn't be as efficient as something written in assembly, C, or even Python."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
|
|
@ -1,244 +0,0 @@
|
|||
|
||||
# Advent of Code 2017
|
||||
|
||||
## December 5th
|
||||
...a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list.
|
||||
|
||||
In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered.
|
||||
|
||||
For example, consider the following list of jump offsets:
|
||||
|
||||
0
|
||||
3
|
||||
0
|
||||
1
|
||||
-3
|
||||
|
||||
Positive jumps ("forward") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found:
|
||||
|
||||
* (0) 3 0 1 -3 - before we have taken any steps.
|
||||
* (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.
|
||||
* 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.
|
||||
* 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind.
|
||||
* 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2.
|
||||
* 2 5 0 1 -2 - jump 4 steps forward, escaping the maze.
|
||||
|
||||
In this example, the exit is reached in 5 steps.
|
||||
|
||||
How many steps does it take to reach the exit?
|
||||
|
||||
## Breakdown
|
||||
For now, I'm going to assume a starting state with the size of the sequence pre-computed. We need it to define the exit condition and it is a trivial preamble to generate it. We then need and `index` and a `step-count`, which are both initially zero. Then we have the sequence itself, and some recursive function `F` that does the work.
|
||||
|
||||
size index step-count [...] F
|
||||
-----------------------------------
|
||||
step-count
|
||||
|
||||
F == [P] [T] [R1] [R2] genrec
|
||||
|
||||
Later on I was thinking about it and the Forth heuristic came to mind, to wit: four things on the stack are kind of much. Immediately I realized that the size properly belongs in the predicate of `F`! D'oh!
|
||||
|
||||
index step-count [...] F
|
||||
------------------------------
|
||||
step-count
|
||||
|
||||
So, let's start by nailing down the predicate:
|
||||
|
||||
F == [P] [T] [R1] [R2] genrec
|
||||
== [P] [T] [R1 [F] R2] ifte
|
||||
|
||||
0 0 [0 3 0 1 -3] popop 5 >=
|
||||
|
||||
P == popop 5 >=
|
||||
|
||||
Now we need the else-part:
|
||||
|
||||
index step-count [0 3 0 1 -3] roll< popop
|
||||
|
||||
E == roll< popop
|
||||
|
||||
Last but not least, the recursive branch
|
||||
|
||||
0 0 [0 3 0 1 -3] R1 [F] R2
|
||||
|
||||
The `R1` function has a big job:
|
||||
|
||||
R1 == get the value at index
|
||||
increment the value at the index
|
||||
add the value gotten to the index
|
||||
increment the step count
|
||||
|
||||
The only tricky thing there is incrementing an integer in the sequence. Joy sequences are not particularly good for random access. We could encode the list of jump offsets in a big integer and use math to do the processing for a good speed-up, but it still wouldn't beat the performance of e.g. a mutable array. This is just one of those places where "plain vanilla" Joypy doesn't shine (in default performance. The legendary *Sufficiently-Smart Compiler* would of course rewrite this function to use an array "under the hood".)
|
||||
|
||||
In the meantime, I'm going to write a primitive function that just does what we need.
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import D, J, V, define
|
||||
from joy.library import SimpleFunctionWrapper
|
||||
from joy.utils.stack import list_to_stack
|
||||
|
||||
|
||||
@SimpleFunctionWrapper
|
||||
def incr_at(stack):
|
||||
'''Given a index and a sequence of integers, increment the integer at the index.
|
||||
|
||||
E.g.:
|
||||
|
||||
3 [0 1 2 3 4 5] incr_at
|
||||
-----------------------------
|
||||
[0 1 2 4 4 5]
|
||||
|
||||
'''
|
||||
sequence, (i, stack) = stack
|
||||
mem = []
|
||||
while i >= 0:
|
||||
term, sequence = sequence
|
||||
mem.append(term)
|
||||
i -= 1
|
||||
mem[-1] += 1
|
||||
return list_to_stack(mem, sequence), stack
|
||||
|
||||
|
||||
D['incr_at'] = incr_at
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('3 [0 1 2 3 4 5] incr_at')
|
||||
```
|
||||
|
||||
[0 1 2 4 4 5]
|
||||
|
||||
|
||||
### get the value at index
|
||||
|
||||
3 0 [0 1 2 3 4] [roll< at] nullary
|
||||
3 0 [0 1 2 n 4] n
|
||||
|
||||
### increment the value at the index
|
||||
|
||||
3 0 [0 1 2 n 4] n [Q] dip
|
||||
3 0 [0 1 2 n 4] Q n
|
||||
3 0 [0 1 2 n 4] [popd incr_at] unary n
|
||||
3 0 [0 1 2 n+1 4] n
|
||||
|
||||
### add the value gotten to the index
|
||||
|
||||
3 0 [0 1 2 n+1 4] n [+] cons dipd
|
||||
3 0 [0 1 2 n+1 4] [n +] dipd
|
||||
3 n + 0 [0 1 2 n+1 4]
|
||||
3+n 0 [0 1 2 n+1 4]
|
||||
|
||||
### increment the step count
|
||||
|
||||
3+n 0 [0 1 2 n+1 4] [++] dip
|
||||
3+n 1 [0 1 2 n+1 4]
|
||||
|
||||
### All together now...
|
||||
|
||||
get_value == [roll< at] nullary
|
||||
incr_value == [[popd incr_at] unary] dip
|
||||
add_value == [+] cons dipd
|
||||
incr_step_count == [++] dip
|
||||
|
||||
R1 == get_value incr_value add_value incr_step_count
|
||||
|
||||
F == [P] [T] [R1] primrec
|
||||
|
||||
F == [popop !size! >=] [roll< pop] [get_value incr_value add_value incr_step_count] primrec
|
||||
|
||||
|
||||
```python
|
||||
from joy.library import DefinitionWrapper
|
||||
|
||||
|
||||
DefinitionWrapper.add_definitions('''
|
||||
|
||||
get_value == [roll< at] nullary
|
||||
incr_value == [[popd incr_at] unary] dip
|
||||
add_value == [+] cons dipd
|
||||
incr_step_count == [++] dip
|
||||
|
||||
AoC2017.5.0 == get_value incr_value add_value incr_step_count
|
||||
|
||||
''', D)
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
define('F == [popop 5 >=] [roll< popop] [AoC2017.5.0] primrec')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('0 0 [0 3 0 1 -3] F')
|
||||
```
|
||||
|
||||
5
|
||||
|
||||
|
||||
### Preamble for setting up predicate, `index`, and `step-count`
|
||||
|
||||
We want to go from this to this:
|
||||
|
||||
[...] AoC2017.5.preamble
|
||||
------------------------------
|
||||
0 0 [...] [popop n >=]
|
||||
|
||||
Where `n` is the size of the sequence.
|
||||
|
||||
The first part is obviously `0 0 roll<`, then `dup size`:
|
||||
|
||||
[...] 0 0 roll< dup size
|
||||
0 0 [...] n
|
||||
|
||||
Then:
|
||||
|
||||
0 0 [...] n [>=] cons [popop] swoncat
|
||||
|
||||
So:
|
||||
|
||||
init-index-and-step-count == 0 0 roll<
|
||||
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||
|
||||
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||
|
||||
|
||||
```python
|
||||
DefinitionWrapper.add_definitions('''
|
||||
|
||||
init-index-and-step-count == 0 0 roll<
|
||||
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||
|
||||
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||
|
||||
AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec
|
||||
|
||||
''', D)
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[0 3 0 1 -3] AoC2017.5')
|
||||
```
|
||||
|
||||
5
|
||||
|
||||
|
||||
|
||||
AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec
|
||||
|
||||
AoC2017.5.0 == get_value incr_value add_value incr_step_count
|
||||
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||
|
||||
get_value == [roll< at] nullary
|
||||
incr_value == [[popd incr_at] unary] dip
|
||||
add_value == [+] cons dipd
|
||||
incr_step_count == [++] dip
|
||||
|
||||
init-index-and-step-count == 0 0 roll<
|
||||
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||
|
||||
|
||||
This is by far the largest program I have yet written in Joy. Even with the `incr_at` function it is still a bear. There may be an arrangement of the parameters that would permit more elegant definitions, but it still wouldn't be as efficient as something written in assembly, C, or even Python.
|
||||
|
|
@ -1,324 +0,0 @@
|
|||
|
||||
Advent of Code 2017
|
||||
===================
|
||||
|
||||
December 5th
|
||||
------------
|
||||
|
||||
...a list of the offsets for each jump. Jumps are relative: -1 moves to
|
||||
the previous instruction, and 2 skips the next one. Start at the first
|
||||
instruction in the list. The goal is to follow the jumps until one leads
|
||||
outside the list.
|
||||
|
||||
In addition, these instructions are a little strange; after each jump,
|
||||
the offset of that instruction increases by 1. So, if you come across an
|
||||
offset of 3, you would move three instructions forward, but change it to
|
||||
a 4 for the next time it is encountered.
|
||||
|
||||
For example, consider the following list of jump offsets:
|
||||
|
||||
::
|
||||
|
||||
0
|
||||
3
|
||||
0
|
||||
1
|
||||
-3
|
||||
|
||||
Positive jumps ("forward") move downward; negative jumps move upward.
|
||||
For legibility in this example, these offset values will be written all
|
||||
on one line, with the current instruction marked in parentheses. The
|
||||
following steps would be taken before an exit is found:
|
||||
|
||||
-
|
||||
|
||||
(0) 3 0 1 -3 - before we have taken any steps.
|
||||
|
||||
-
|
||||
|
||||
(1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all).
|
||||
Fortunately, the instruction is then incremented to 1.
|
||||
|
||||
- 2 (3) 0 1 -3 - step forward because of the instruction we just
|
||||
modified. The first instruction is incremented again, now to 2.
|
||||
- 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind.
|
||||
- 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2.
|
||||
- 2 5 0 1 -2 - jump 4 steps forward, escaping the maze.
|
||||
|
||||
In this example, the exit is reached in 5 steps.
|
||||
|
||||
How many steps does it take to reach the exit?
|
||||
|
||||
Breakdown
|
||||
---------
|
||||
|
||||
For now, I'm going to assume a starting state with the size of the
|
||||
sequence pre-computed. We need it to define the exit condition and it is
|
||||
a trivial preamble to generate it. We then need and ``index`` and a
|
||||
``step-count``, which are both initially zero. Then we have the sequence
|
||||
itself, and some recursive function ``F`` that does the work.
|
||||
|
||||
::
|
||||
|
||||
size index step-count [...] F
|
||||
-----------------------------------
|
||||
step-count
|
||||
|
||||
F == [P] [T] [R1] [R2] genrec
|
||||
|
||||
Later on I was thinking about it and the Forth heuristic came to mind,
|
||||
to wit: four things on the stack are kind of much. Immediately I
|
||||
realized that the size properly belongs in the predicate of ``F``! D'oh!
|
||||
|
||||
::
|
||||
|
||||
index step-count [...] F
|
||||
------------------------------
|
||||
step-count
|
||||
|
||||
So, let's start by nailing down the predicate:
|
||||
|
||||
::
|
||||
|
||||
F == [P] [T] [R1] [R2] genrec
|
||||
== [P] [T] [R1 [F] R2] ifte
|
||||
|
||||
0 0 [0 3 0 1 -3] popop 5 >=
|
||||
|
||||
P == popop 5 >=
|
||||
|
||||
Now we need the else-part:
|
||||
|
||||
::
|
||||
|
||||
index step-count [0 3 0 1 -3] roll< popop
|
||||
|
||||
E == roll< popop
|
||||
|
||||
Last but not least, the recursive branch
|
||||
|
||||
::
|
||||
|
||||
0 0 [0 3 0 1 -3] R1 [F] R2
|
||||
|
||||
The ``R1`` function has a big job:
|
||||
|
||||
::
|
||||
|
||||
R1 == get the value at index
|
||||
increment the value at the index
|
||||
add the value gotten to the index
|
||||
increment the step count
|
||||
|
||||
The only tricky thing there is incrementing an integer in the sequence.
|
||||
Joy sequences are not particularly good for random access. We could
|
||||
encode the list of jump offsets in a big integer and use math to do the
|
||||
processing for a good speed-up, but it still wouldn't beat the
|
||||
performance of e.g. a mutable array. This is just one of those places
|
||||
where "plain vanilla" Joypy doesn't shine (in default performance. The
|
||||
legendary *Sufficiently-Smart Compiler* would of course rewrite this
|
||||
function to use an array "under the hood".)
|
||||
|
||||
In the meantime, I'm going to write a primitive function that just does
|
||||
what we need.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import D, J, V, define
|
||||
from joy.library import SimpleFunctionWrapper
|
||||
from joy.utils.stack import list_to_stack
|
||||
|
||||
|
||||
@SimpleFunctionWrapper
|
||||
def incr_at(stack):
|
||||
'''Given a index and a sequence of integers, increment the integer at the index.
|
||||
|
||||
E.g.:
|
||||
|
||||
3 [0 1 2 3 4 5] incr_at
|
||||
-----------------------------
|
||||
[0 1 2 4 4 5]
|
||||
|
||||
'''
|
||||
sequence, (i, stack) = stack
|
||||
mem = []
|
||||
while i >= 0:
|
||||
term, sequence = sequence
|
||||
mem.append(term)
|
||||
i -= 1
|
||||
mem[-1] += 1
|
||||
return list_to_stack(mem, sequence), stack
|
||||
|
||||
|
||||
D['incr_at'] = incr_at
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('3 [0 1 2 3 4 5] incr_at')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[0 1 2 4 4 5]
|
||||
|
||||
|
||||
get the value at index
|
||||
~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
3 0 [0 1 2 3 4] [roll< at] nullary
|
||||
3 0 [0 1 2 n 4] n
|
||||
|
||||
increment the value at the index
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
3 0 [0 1 2 n 4] n [Q] dip
|
||||
3 0 [0 1 2 n 4] Q n
|
||||
3 0 [0 1 2 n 4] [popd incr_at] unary n
|
||||
3 0 [0 1 2 n+1 4] n
|
||||
|
||||
add the value gotten to the index
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
3 0 [0 1 2 n+1 4] n [+] cons dipd
|
||||
3 0 [0 1 2 n+1 4] [n +] dipd
|
||||
3 n + 0 [0 1 2 n+1 4]
|
||||
3+n 0 [0 1 2 n+1 4]
|
||||
|
||||
increment the step count
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
3+n 0 [0 1 2 n+1 4] [++] dip
|
||||
3+n 1 [0 1 2 n+1 4]
|
||||
|
||||
All together now...
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
get_value == [roll< at] nullary
|
||||
incr_value == [[popd incr_at] unary] dip
|
||||
add_value == [+] cons dipd
|
||||
incr_step_count == [++] dip
|
||||
|
||||
R1 == get_value incr_value add_value incr_step_count
|
||||
|
||||
F == [P] [T] [R1] primrec
|
||||
|
||||
F == [popop !size! >=] [roll< pop] [get_value incr_value add_value incr_step_count] primrec
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from joy.library import DefinitionWrapper
|
||||
|
||||
|
||||
DefinitionWrapper.add_definitions('''
|
||||
|
||||
get_value == [roll< at] nullary
|
||||
incr_value == [[popd incr_at] unary] dip
|
||||
add_value == [+] cons dipd
|
||||
incr_step_count == [++] dip
|
||||
|
||||
AoC2017.5.0 == get_value incr_value add_value incr_step_count
|
||||
|
||||
''', D)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('F == [popop 5 >=] [roll< popop] [AoC2017.5.0] primrec')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('0 0 [0 3 0 1 -3] F')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
5
|
||||
|
||||
|
||||
Preamble for setting up predicate, ``index``, and ``step-count``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
We want to go from this to this:
|
||||
|
||||
::
|
||||
|
||||
[...] AoC2017.5.preamble
|
||||
------------------------------
|
||||
0 0 [...] [popop n >=]
|
||||
|
||||
Where ``n`` is the size of the sequence.
|
||||
|
||||
The first part is obviously ``0 0 roll<``, then ``dup size``:
|
||||
|
||||
::
|
||||
|
||||
[...] 0 0 roll< dup size
|
||||
0 0 [...] n
|
||||
|
||||
Then:
|
||||
|
||||
::
|
||||
|
||||
0 0 [...] n [>=] cons [popop] swoncat
|
||||
|
||||
So:
|
||||
|
||||
::
|
||||
|
||||
init-index-and-step-count == 0 0 roll<
|
||||
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||
|
||||
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
DefinitionWrapper.add_definitions('''
|
||||
|
||||
init-index-and-step-count == 0 0 roll<
|
||||
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||
|
||||
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||
|
||||
AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec
|
||||
|
||||
''', D)
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 3 0 1 -3] AoC2017.5')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
5
|
||||
|
||||
|
||||
::
|
||||
|
||||
AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec
|
||||
|
||||
AoC2017.5.0 == get_value incr_value add_value incr_step_count
|
||||
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||
|
||||
get_value == [roll< at] nullary
|
||||
incr_value == [[popd incr_at] unary] dip
|
||||
add_value == [+] cons dipd
|
||||
incr_step_count == [++] dip
|
||||
|
||||
init-index-and-step-count == 0 0 roll<
|
||||
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||
|
||||
This is by far the largest program I have yet written in Joy. Even with
|
||||
the ``incr_at`` function it is still a bear. There may be an arrangement
|
||||
of the parameters that would permit more elegant definitions, but it
|
||||
still wouldn't be as efficient as something written in assembly, C, or
|
||||
even Python.
|
||||
|
|
@ -1,457 +0,0 @@
|
|||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Advent of Code 2017\n",
|
||||
"\n",
|
||||
"## December 6th\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" [0 2 7 0] dup max\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from notebook_preamble import D, J, V, define"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[0 2 7 0] 7\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 2 7 0] dup max')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from joy.library import SimpleFunctionWrapper\n",
|
||||
"from joy.utils.stack import list_to_stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@SimpleFunctionWrapper\n",
|
||||
"def index_of(stack):\n",
|
||||
" '''Given a sequence and a item, return the index of the item, or -1 if not found.\n",
|
||||
"\n",
|
||||
" E.g.:\n",
|
||||
"\n",
|
||||
" [a b c] a index_of\n",
|
||||
" ------------------------\n",
|
||||
" 0\n",
|
||||
"\n",
|
||||
" [a b c] d index_of\n",
|
||||
" ------------------------\n",
|
||||
" -1\n",
|
||||
"\n",
|
||||
" '''\n",
|
||||
" item, (sequence, stack) = stack\n",
|
||||
" i = 0\n",
|
||||
" while sequence:\n",
|
||||
" term, sequence = sequence\n",
|
||||
" if term == item:\n",
|
||||
" break\n",
|
||||
" i += 1\n",
|
||||
" else:\n",
|
||||
" i = -1\n",
|
||||
" return i, stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"D['index_of'] = index_of"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"2\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 2 7 0] 7 index_of')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"-1\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 2 7 0] 23 index_of')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Starting at `index` distribute `count` \"blocks\" to the \"banks\" in the sequence.\n",
|
||||
"\n",
|
||||
" [...] count index distribute\n",
|
||||
" ----------------------------\n",
|
||||
" [...]\n",
|
||||
"\n",
|
||||
"This seems like it would be a PITA to implement in Joypy..."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from joy.utils.stack import iter_stack, list_to_stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@SimpleFunctionWrapper\n",
|
||||
"def distribute(stack):\n",
|
||||
" '''Starting at index+1 distribute count \"blocks\" to the \"banks\" in the sequence.\n",
|
||||
"\n",
|
||||
" [...] count index distribute\n",
|
||||
" ----------------------------\n",
|
||||
" [...]\n",
|
||||
"\n",
|
||||
" '''\n",
|
||||
" index, (count, (sequence, stack)) = stack\n",
|
||||
" assert count >= 0\n",
|
||||
" cheat = list(iter_stack(sequence))\n",
|
||||
" n = len(cheat)\n",
|
||||
" assert index < n\n",
|
||||
" cheat[index] = 0\n",
|
||||
" while count:\n",
|
||||
" index += 1\n",
|
||||
" index %= n\n",
|
||||
" cheat[index] += 1\n",
|
||||
" count -= 1\n",
|
||||
" return list_to_stack(cheat), stack\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"D['distribute'] = distribute"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[2 4 1 2]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 2 7 0] dup max [index_of] nullary distribute')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[3 1 2 3]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[2 4 1 2] dup max [index_of] nullary distribute')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[0 2 3 4]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[3 1 2 3] dup max [index_of] nullary distribute')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[1 3 4 1]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 2 3 4] dup max [index_of] nullary distribute')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[2 4 1 2]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 3 4 1] dup max [index_of] nullary distribute')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Recalling \"Generator Programs\"\n",
|
||||
"\n",
|
||||
" [a F] x\n",
|
||||
" [a F] a F \n",
|
||||
" \n",
|
||||
" [a F] a swap [C] dip rest cons\n",
|
||||
" a [a F] [C] dip rest cons\n",
|
||||
" a C [a F] rest cons\n",
|
||||
" a C [F] cons\n",
|
||||
"\n",
|
||||
" w/ C == dup G\n",
|
||||
"\n",
|
||||
" a dup G [F] cons\n",
|
||||
" a a G [F] cons\n",
|
||||
"\n",
|
||||
" w/ G == dup max [index_of] nullary distribute"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 12,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('direco == dip rest cons')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 13,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('G == [direco] cons [swap] swoncat cons')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 14,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('make_distributor == [dup dup max [index_of] nullary distribute] G')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[0 2 7 0] [2 4 1 2] [3 1 2 3] [0 2 3 4] [1 3 4 1] [2 4 1 2]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 2 7 0] make_distributor 6 [x] times pop')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### A function to drive a generator and count how many states before a repeat.\n",
|
||||
"First draft:\n",
|
||||
"\n",
|
||||
" [] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||
"\n",
|
||||
"(?)\n",
|
||||
"\n",
|
||||
" [] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||
" [] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||
" [] [...] [GEN] pop index_of 0 >=\n",
|
||||
" [] [...] index_of 0 >=\n",
|
||||
" -1 0 >=\n",
|
||||
" False\n",
|
||||
"\n",
|
||||
"Base case\n",
|
||||
"\n",
|
||||
" [] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||
" [] [...] [GEN] pop size --\n",
|
||||
" [] [...] size --\n",
|
||||
" [] [...] size --\n",
|
||||
"\n",
|
||||
"A mistake, `popop` and no need for `--`\n",
|
||||
"\n",
|
||||
" [] [...] [GEN] popop size\n",
|
||||
" [] size\n",
|
||||
" n\n",
|
||||
"\n",
|
||||
"Recursive case\n",
|
||||
"\n",
|
||||
" [] [...] [GEN] [pop index_of 0 >=] [popop size] [[swons] dip x] primrec\n",
|
||||
" [] [...] [GEN] [swons] dip x F\n",
|
||||
" [] [...] swons [GEN] x F\n",
|
||||
" [[...]] [GEN] x F\n",
|
||||
" [[...]] [...] [GEN] F\n",
|
||||
"\n",
|
||||
" [[...]] [...] [GEN] F\n",
|
||||
"\n",
|
||||
"What have we learned?\n",
|
||||
"\n",
|
||||
" F == [pop index_of 0 >=] [popop size] [[swons] dip x] primrec"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 16,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('count_states == [] swap x [pop index_of 0 >=] [popop size] [[swons] dip x] primrec')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 17,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"define('AoC2017.6 == make_distributor count_states')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 18,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"5\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[0 2 7 0] AoC2017.6')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"4\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[1 1 1] AoC2017.6')"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 20,
|
||||
"metadata": {
|
||||
"scrolled": false
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"15\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"J('[8 0 0 0 0 0] AoC2017.6')"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 2",
|
||||
"language": "python",
|
||||
"name": "python2"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 2
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython2",
|
||||
"version": "2.7.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
|
|
@ -1,267 +0,0 @@
|
|||
|
||||
# Advent of Code 2017
|
||||
|
||||
## December 6th
|
||||
|
||||
|
||||
[0 2 7 0] dup max
|
||||
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import D, J, V, define
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[0 2 7 0] dup max')
|
||||
```
|
||||
|
||||
[0 2 7 0] 7
|
||||
|
||||
|
||||
|
||||
```python
|
||||
from joy.library import SimpleFunctionWrapper
|
||||
from joy.utils.stack import list_to_stack
|
||||
|
||||
|
||||
@SimpleFunctionWrapper
|
||||
def index_of(stack):
|
||||
'''Given a sequence and a item, return the index of the item, or -1 if not found.
|
||||
|
||||
E.g.:
|
||||
|
||||
[a b c] a index_of
|
||||
------------------------
|
||||
0
|
||||
|
||||
[a b c] d index_of
|
||||
------------------------
|
||||
-1
|
||||
|
||||
'''
|
||||
item, (sequence, stack) = stack
|
||||
i = 0
|
||||
while sequence:
|
||||
term, sequence = sequence
|
||||
if term == item:
|
||||
break
|
||||
i += 1
|
||||
else:
|
||||
i = -1
|
||||
return i, stack
|
||||
|
||||
|
||||
D['index_of'] = index_of
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[0 2 7 0] 7 index_of')
|
||||
```
|
||||
|
||||
2
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[0 2 7 0] 23 index_of')
|
||||
```
|
||||
|
||||
-1
|
||||
|
||||
|
||||
Starting at `index` distribute `count` "blocks" to the "banks" in the sequence.
|
||||
|
||||
[...] count index distribute
|
||||
----------------------------
|
||||
[...]
|
||||
|
||||
This seems like it would be a PITA to implement in Joypy...
|
||||
|
||||
|
||||
```python
|
||||
from joy.utils.stack import iter_stack, list_to_stack
|
||||
|
||||
|
||||
@SimpleFunctionWrapper
|
||||
def distribute(stack):
|
||||
'''Starting at index+1 distribute count "blocks" to the "banks" in the sequence.
|
||||
|
||||
[...] count index distribute
|
||||
----------------------------
|
||||
[...]
|
||||
|
||||
'''
|
||||
index, (count, (sequence, stack)) = stack
|
||||
assert count >= 0
|
||||
cheat = list(iter_stack(sequence))
|
||||
n = len(cheat)
|
||||
assert index < n
|
||||
cheat[index] = 0
|
||||
while count:
|
||||
index += 1
|
||||
index %= n
|
||||
cheat[index] += 1
|
||||
count -= 1
|
||||
return list_to_stack(cheat), stack
|
||||
|
||||
|
||||
D['distribute'] = distribute
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[0 2 7 0] dup max [index_of] nullary distribute')
|
||||
```
|
||||
|
||||
[2 4 1 2]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[2 4 1 2] dup max [index_of] nullary distribute')
|
||||
```
|
||||
|
||||
[3 1 2 3]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[3 1 2 3] dup max [index_of] nullary distribute')
|
||||
```
|
||||
|
||||
[0 2 3 4]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[0 2 3 4] dup max [index_of] nullary distribute')
|
||||
```
|
||||
|
||||
[1 3 4 1]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 3 4 1] dup max [index_of] nullary distribute')
|
||||
```
|
||||
|
||||
[2 4 1 2]
|
||||
|
||||
|
||||
### Recalling "Generator Programs"
|
||||
|
||||
[a F] x
|
||||
[a F] a F
|
||||
|
||||
[a F] a swap [C] dip rest cons
|
||||
a [a F] [C] dip rest cons
|
||||
a C [a F] rest cons
|
||||
a C [F] cons
|
||||
|
||||
w/ C == dup G
|
||||
|
||||
a dup G [F] cons
|
||||
a a G [F] cons
|
||||
|
||||
w/ G == dup max [index_of] nullary distribute
|
||||
|
||||
|
||||
```python
|
||||
define('direco == dip rest cons')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
define('G == [direco] cons [swap] swoncat cons')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
define('make_distributor == [dup dup max [index_of] nullary distribute] G')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[0 2 7 0] make_distributor 6 [x] times pop')
|
||||
```
|
||||
|
||||
[0 2 7 0] [2 4 1 2] [3 1 2 3] [0 2 3 4] [1 3 4 1] [2 4 1 2]
|
||||
|
||||
|
||||
### A function to drive a generator and count how many states before a repeat.
|
||||
First draft:
|
||||
|
||||
[] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
|
||||
(?)
|
||||
|
||||
[] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
[] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
[] [...] [GEN] pop index_of 0 >=
|
||||
[] [...] index_of 0 >=
|
||||
-1 0 >=
|
||||
False
|
||||
|
||||
Base case
|
||||
|
||||
[] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
[] [...] [GEN] pop size --
|
||||
[] [...] size --
|
||||
[] [...] size --
|
||||
|
||||
A mistake, `popop` and no need for `--`
|
||||
|
||||
[] [...] [GEN] popop size
|
||||
[] size
|
||||
n
|
||||
|
||||
Recursive case
|
||||
|
||||
[] [...] [GEN] [pop index_of 0 >=] [popop size] [[swons] dip x] primrec
|
||||
[] [...] [GEN] [swons] dip x F
|
||||
[] [...] swons [GEN] x F
|
||||
[[...]] [GEN] x F
|
||||
[[...]] [...] [GEN] F
|
||||
|
||||
[[...]] [...] [GEN] F
|
||||
|
||||
What have we learned?
|
||||
|
||||
F == [pop index_of 0 >=] [popop size] [[swons] dip x] primrec
|
||||
|
||||
|
||||
```python
|
||||
define('count_states == [] swap x [pop index_of 0 >=] [popop size] [[swons] dip x] primrec')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
define('AoC2017.6 == make_distributor count_states')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[0 2 7 0] AoC2017.6')
|
||||
```
|
||||
|
||||
5
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 1 1] AoC2017.6')
|
||||
```
|
||||
|
||||
4
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[8 0 0 0 0 0] AoC2017.6')
|
||||
```
|
||||
|
||||
15
|
||||
|
||||
|
|
@ -1,305 +0,0 @@
|
|||
|
||||
Advent of Code 2017
|
||||
===================
|
||||
|
||||
December 6th
|
||||
------------
|
||||
|
||||
::
|
||||
|
||||
[0 2 7 0] dup max
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import D, J, V, define
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 2 7 0] dup max')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[0 2 7 0] 7
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from joy.library import SimpleFunctionWrapper
|
||||
from joy.utils.stack import list_to_stack
|
||||
|
||||
|
||||
@SimpleFunctionWrapper
|
||||
def index_of(stack):
|
||||
'''Given a sequence and a item, return the index of the item, or -1 if not found.
|
||||
|
||||
E.g.:
|
||||
|
||||
[a b c] a index_of
|
||||
------------------------
|
||||
0
|
||||
|
||||
[a b c] d index_of
|
||||
------------------------
|
||||
-1
|
||||
|
||||
'''
|
||||
item, (sequence, stack) = stack
|
||||
i = 0
|
||||
while sequence:
|
||||
term, sequence = sequence
|
||||
if term == item:
|
||||
break
|
||||
i += 1
|
||||
else:
|
||||
i = -1
|
||||
return i, stack
|
||||
|
||||
|
||||
D['index_of'] = index_of
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 2 7 0] 7 index_of')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 2 7 0] 23 index_of')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
-1
|
||||
|
||||
|
||||
Starting at ``index`` distribute ``count`` "blocks" to the "banks" in
|
||||
the sequence.
|
||||
|
||||
::
|
||||
|
||||
[...] count index distribute
|
||||
----------------------------
|
||||
[...]
|
||||
|
||||
This seems like it would be a PITA to implement in Joypy...
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from joy.utils.stack import iter_stack, list_to_stack
|
||||
|
||||
|
||||
@SimpleFunctionWrapper
|
||||
def distribute(stack):
|
||||
'''Starting at index+1 distribute count "blocks" to the "banks" in the sequence.
|
||||
|
||||
[...] count index distribute
|
||||
----------------------------
|
||||
[...]
|
||||
|
||||
'''
|
||||
index, (count, (sequence, stack)) = stack
|
||||
assert count >= 0
|
||||
cheat = list(iter_stack(sequence))
|
||||
n = len(cheat)
|
||||
assert index < n
|
||||
cheat[index] = 0
|
||||
while count:
|
||||
index += 1
|
||||
index %= n
|
||||
cheat[index] += 1
|
||||
count -= 1
|
||||
return list_to_stack(cheat), stack
|
||||
|
||||
|
||||
D['distribute'] = distribute
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 2 7 0] dup max [index_of] nullary distribute')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[2 4 1 2]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[2 4 1 2] dup max [index_of] nullary distribute')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[3 1 2 3]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[3 1 2 3] dup max [index_of] nullary distribute')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[0 2 3 4]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 2 3 4] dup max [index_of] nullary distribute')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[1 3 4 1]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 3 4 1] dup max [index_of] nullary distribute')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[2 4 1 2]
|
||||
|
||||
|
||||
Recalling "Generator Programs"
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
[a F] x
|
||||
[a F] a F
|
||||
|
||||
[a F] a swap [C] dip rest cons
|
||||
a [a F] [C] dip rest cons
|
||||
a C [a F] rest cons
|
||||
a C [F] cons
|
||||
|
||||
w/ C == dup G
|
||||
|
||||
a dup G [F] cons
|
||||
a a G [F] cons
|
||||
|
||||
w/ G == dup max [index_of] nullary distribute
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('direco == dip rest cons')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('G == [direco] cons [swap] swoncat cons')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('make_distributor == [dup dup max [index_of] nullary distribute] G')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 2 7 0] make_distributor 6 [x] times pop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[0 2 7 0] [2 4 1 2] [3 1 2 3] [0 2 3 4] [1 3 4 1] [2 4 1 2]
|
||||
|
||||
|
||||
A function to drive a generator and count how many states before a repeat.
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
First draft:
|
||||
|
||||
::
|
||||
|
||||
[] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
|
||||
(?)
|
||||
|
||||
::
|
||||
|
||||
[] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
[] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
[] [...] [GEN] pop index_of 0 >=
|
||||
[] [...] index_of 0 >=
|
||||
-1 0 >=
|
||||
False
|
||||
|
||||
Base case
|
||||
|
||||
::
|
||||
|
||||
[] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||
[] [...] [GEN] pop size --
|
||||
[] [...] size --
|
||||
[] [...] size --
|
||||
|
||||
A mistake, ``popop`` and no need for ``--``
|
||||
|
||||
::
|
||||
|
||||
[] [...] [GEN] popop size
|
||||
[] size
|
||||
n
|
||||
|
||||
Recursive case
|
||||
|
||||
::
|
||||
|
||||
[] [...] [GEN] [pop index_of 0 >=] [popop size] [[swons] dip x] primrec
|
||||
[] [...] [GEN] [swons] dip x F
|
||||
[] [...] swons [GEN] x F
|
||||
[[...]] [GEN] x F
|
||||
[[...]] [...] [GEN] F
|
||||
|
||||
[[...]] [...] [GEN] F
|
||||
|
||||
What have we learned?
|
||||
|
||||
::
|
||||
|
||||
F == [pop index_of 0 >=] [popop size] [[swons] dip x] primrec
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('count_states == [] swap x [pop index_of 0 >=] [popop size] [[swons] dip x] primrec')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('AoC2017.6 == make_distributor count_states')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 2 7 0] AoC2017.6')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
5
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 1 1] AoC2017.6')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
4
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[8 0 0 0 0 0] AoC2017.6')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
15
|
||||
|
||||
469
docs/Document.md
|
|
@ -1,469 +0,0 @@
|
|||
|
||||
# Joy
|
||||
|
||||
This document is written to capture, at least crudely, the scope of application for Joy and the Joypy implementation. It kind of expects that you have some familiarity with Joy already.
|
||||
|
||||
It is vaguely organized, in a pile.
|
||||
|
||||
|
||||
## Syntax
|
||||
|
||||
Very simple syntax. Could be specified as a sequence of one or more terms:
|
||||
|
||||
joy ::= term term*
|
||||
|
||||
Conceptually, all terms are unary functions `F :: stack -> stack` that accept a stack and return a stack. But we immediately differentiate between literals (of a few kinds), functions, and combinators (which like higher-order functions.)
|
||||
|
||||
|
||||
### In Joypy there are currently four literal types.
|
||||
|
||||
First we have the types borrowed from the underlying Python semantics. **Strings** (byte and Unicode with nuances depending on whether you're running under Python 2 or 3), **ints**, and **floats**. Then there is the **sequence** type, aka "quote", "list", etc... In joy it is represented by enclosing zero or more terms in square brackets:
|
||||
|
||||
sequence :== '[' term* ']'
|
||||
|
||||
(In Joypy it is implemented as a cons-list. All datastructures in Joypy are built out of this single sequence type, including the stack and expression. I could include Python `frozenset` but I don't.)
|
||||
|
||||
literal ::= string | int | float | sequence
|
||||
|
||||
Functions accept zero or more arguments from the stack and push back zero or more results.
|
||||
|
||||
Combinators are functions one or more of the arguments to which are quotes containing joy expressions, and which then execute one or more of their quoted arguments to effect their function.
|
||||
|
||||
term ::= literal | function | combinator
|
||||
|
||||
The code for the parser is in `joy/parser.py`.
|
||||
|
||||
|
||||
## Semantics
|
||||
|
||||
In Joy juxtaposition of symbols is composition of functions. That means that `F G` syntactically is `G(F(...))` semantically.
|
||||
|
||||
As it says in the [Wikipedia entry for Joypy](https://en.wikipedia.org/wiki/Joy_%28programming_language%29):
|
||||
|
||||
"In Joy, the meaning function is a homomorphism from the syntactic monoid onto the semantic monoid. That is, the syntactic relation of concatenation of symbols maps directly onto the semantic relation of composition of functions."
|
||||
|
||||
Isn't that nice?
|
||||
|
||||
|
||||
## Joypy Continuation-Passing Style
|
||||
|
||||
In Joypy all the combinators work by modifying the pending expression. We have enlarged the definition of function to be from a two-tuple of `(stack, expression)` to another such two-tuple:
|
||||
|
||||
F :: (stack, expression) -> (stack, expression)
|
||||
|
||||
Simple functions ignore the expression and pass it through unchanged, combinators do not. They can modify it and this is enough to define control-flow and other operators.
|
||||
|
||||
(Actually... In Joypy the functions all also include a dictionary parameter. This allows for functions like `print_words` and `help`. It also allows for the definition of a `define` function which would let Joy code add new definitions to the dictionary during evaluation, but this is an area I am leaving unexplored at least for now. It is essentially name-binding (variables) sneaking in, breaking the purity of the system.)
|
||||
|
||||
|
||||
## Evaluation
|
||||
|
||||
The joy interpreter is a very simple loop. As long as the expression is non-empty the interpreter pops the next term and checks it, if it's a literal it's pushed onto the stack, if it's a function or combinator the interpreter calls it passing the current stack and expression, which are then replaced by whatever the function or combinator returns.
|
||||
|
||||
There is no call stack. All state is kept either on the stack or in the pending expression. At each interpreter iteration the stack and expression are complete. (They can be pickled, saved to disc or sent over the network, and reconstituted at any time, etc...)
|
||||
|
||||
|
||||
# Methods of Meta-programming
|
||||
|
||||
Joy seems to lend itself to several complementary forms of meta-programming to develop more-efficient versions of functions.
|
||||
|
||||
|
||||
## Compiling definitions.
|
||||
|
||||
Due to the fact that "juxtaposition of symbols is composition of functions" the *simplest* way to "compile" the Joy expression `F G` would be the Python expression:
|
||||
|
||||
lambda s, e, d: G(*F(s, e, d))
|
||||
|
||||
This produces a new unnamed function that delivers the output of `F` directly to `G` without passing back through the interpreter loop.
|
||||
|
||||
If we wanted to do more work than that, we could inspect the bytecode of the two Python functions, figure out how they name their arguments, and attempt to produce new bytecode that corresponds to the composition of them. This is a little beyond me at the moment, but it's not unrealistic given enough time and attention.
|
||||
|
||||
It will usually be easier to manually write new custom words. For example, the "plus or minus" operator `pm`, defined as:
|
||||
|
||||
pm == [+] [-] cleave popdd
|
||||
|
||||
Can be implemented in Python as:
|
||||
|
||||
@SimpleFunctionWrapper
|
||||
def pm(stack):
|
||||
a, (b, stack) = stack
|
||||
p = b + a
|
||||
m = b - a
|
||||
return m, (p, stack)
|
||||
|
||||
Code that uses `pm` will will work the same but more quickly if the "compiled" version is inscribed in the dictionary.
|
||||
|
||||
It would be remiss not to mention **Cython** in this connection. Many Joy functions can be transparently compiled down to machine code.
|
||||
|
||||
Beyond the above, it should be possible to make use of much of the existing body of knowledge for compiling *functional programming* languages to machine code for making an actual Joy compiler. Joy omits many "features" that are common to most other languages, lambda abstraction and `let` statements for example. I have not had the time to investigate compilation of Joy in any depth so far, but I have high hopes. It should be possible (and most of the details will have been already worked out in other languages) to go from e.g. the definition form of `pm` to the Python form automatically.
|
||||
|
||||
|
||||
## Partial Evaluation
|
||||
|
||||
Cf. "Futamura projections"
|
||||
|
||||
["partial evaluation is a technique for several different types of program optimization by specialization. The most straightforward application is to produce new programs which run faster than the originals while being guaranteed to behave in the same way."](https://en.wikipedia.org/wiki/Partial_evaluation) ~Wikipedia
|
||||
|
||||
Given a function and some (but not all) of its arguments you can run the interpreter in a speculative fashion and derive new functions that are specializations of the original.
|
||||
|
||||
Example from [Futamura, 1983](https://repository.kulib.kyoto-u.ac.jp/dspace/bitstream/2433/103401/1/0482-14.pdf) of converting a power function to a "to the fifth power" function:
|
||||
|
||||
F(k, u) -> u^k
|
||||
|
||||
I like to use a kind of crude [Gentzen notation](https://en.wikipedia.org/wiki/Natural_deduction) to describe a Joy function's semantics:
|
||||
|
||||
k u F
|
||||
-----------
|
||||
u^k
|
||||
|
||||
Joy function implementation:
|
||||
|
||||
F == 1 [popop 0 !=] [[popop 2 %] [over *] [] ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||
|
||||
This is a bit longer than a definition should be. In practice I would refactor it to be more concise and easily understood.
|
||||
|
||||
In Python for comparison:
|
||||
|
||||
def power(k, u):
|
||||
z = 1
|
||||
while k != 0:
|
||||
if k % 2:
|
||||
z = z * u
|
||||
k = k >> 1
|
||||
u = u * u
|
||||
return z
|
||||
|
||||
Using 5 for `k` and pushing evaluation forward as far as it will go with a sort of "thunk" variable for `u` we arrive at:
|
||||
|
||||
u u u * dup * *
|
||||
|
||||
We can replace the extra occurrences of `u` with `dup` to arrive at a definition for a Joy function that, given a number on the stack, returns that number raised to the fifth power:
|
||||
|
||||
to-the-fifth == dup dup * dup * *
|
||||
|
||||
Here it is in action:
|
||||
|
||||
u dup dup * dup * *
|
||||
u u dup * dup * *
|
||||
u u u * dup * *
|
||||
u u^2 dup * *
|
||||
u u^2 u^2 * *
|
||||
u u^4 *
|
||||
u^5
|
||||
|
||||
See the appendix below for the derivation of the specialized form from the general form.
|
||||
|
||||
It should be possible to write a program `FutamuraI` that works like this:
|
||||
|
||||
[5] [F] FutamuraI
|
||||
-------------------------
|
||||
[dup dup * dup * *]
|
||||
|
||||
|
||||
That is, given the quoted program `[F]` and the argument `5`, it returns the new `to-the-fifth` function in quoted form.
|
||||
|
||||
|
||||
### First Futamura Projection
|
||||
|
||||
A joy interpreter written in Joy is described in the literature (available from the La Trobe archive or the mirror site) so we can apply the program `FutamuraI` to that to get a *residual* program `R` for some program `Q`:
|
||||
|
||||
[Q] [joy] FutamuraI
|
||||
-------------------------
|
||||
[R]
|
||||
|
||||
The expected result is that, for a given input, the runtime of `R` is less than or equal to the runtime of `Q`.
|
||||
|
||||
If we had a partial evaluator for Python we could create a residual program in Python for the Joy program `Q`.
|
||||
|
||||
|
||||
### Second Futamura Projection
|
||||
|
||||
[joy] [FutamuraI] FutamuraI
|
||||
---------------------------------
|
||||
[C]
|
||||
|
||||
Making a compiler by "specializing the specializer for the interpreter".
|
||||
|
||||
|
||||
### Third Futamura Projection
|
||||
|
||||
[FutamuraI] [FutamuraI] FutamuraI
|
||||
---------------------------------------
|
||||
[K]
|
||||
|
||||
"Specializing the specializer for itself yielding a tool that can convert any interpreter to an equivalent compiler"
|
||||
|
||||
[joy] K
|
||||
-------------
|
||||
[C]
|
||||
|
||||
|
||||
|
||||
[Q] [joy] K i
|
||||
-------------------
|
||||
[Q] C
|
||||
-----------
|
||||
[R]
|
||||
|
||||
|
||||
|
||||
|
||||
[K] K -> [K]
|
||||
|
||||
|
||||
|
||||
|
||||
## Super-Compilation
|
||||
|
||||
https://en.wikipedia.org/wiki/Metacompilation
|
||||
|
||||
https://themonadreader.files.wordpress.com/2014/04/super-final.pdf
|
||||
|
||||
This is a little hard to describe succinctly, but you are basically trying to figure out all possible paths through a program and then use that knowledge to improve the code, somehow. (I forget the details, but it's worth including and revisiting.)
|
||||
|
||||
|
||||
## Gödel Machine
|
||||
|
||||
http://people.idsia.ch/~juergen/goedelmachine.html
|
||||
|
||||
https://en.wikipedia.org/wiki/G%C3%B6del_machine
|
||||
|
||||
In Joy it often happens that a new general form is discovered that is semantically equivalent to some other form but that has greater efficiency (at least under some definite conditions.) When this happens we can perform a kind of search-and-replace operation over the whole of the current dictionary (standard library in other languages) and achieve performance gains.
|
||||
|
||||
As an example, the function `[1 >>] dipd [sqr] dip` can be rewritten as `[[1 >>] dip sqr] dip` which, depending on the other optimizations some interpreter might make, could be more efficient. We can generalize this to a pattern-matching rule, something like:
|
||||
|
||||
[F] dipd [G] dip == [[F] dip G] dip
|
||||
|
||||
And we are justified rewriting any occurrence of the pattern on either side to the other if it improves things.
|
||||
|
||||
The above also suggests a new combinator, call it `dipdip` that abstracts the pattern:
|
||||
|
||||
... a b [F] [G] dipdip
|
||||
----------------------------
|
||||
... F a G b
|
||||
|
||||
This permits the compiler to make optimizations without having to work to notice the pattern. The `dipdip` function and the interpreter can work together to do the more efficient thing.
|
||||
|
||||
Joy function definitions form Directed Graphs. Not acyclical though, definition bodies do not contain references to other functions, but rather "Symbols" that name functions, so you can form e.g. two definitions that each make use of the other. Generally speaking though, you don't do this, instead you write definitions that use e.g. `genrec` general recursion combinator.
|
||||
|
||||
Anyway, because Joy code is just a graph it becomes pretty easy to rewrite the graph in ways that preserve the semantics but are more efficient. Doing this in an automated fashion is essentially Schmidhuber's Gödel Machine: Finding and applying provably-correct modifications to the whole system in a self-referential way to create a self-improving general problem solver.
|
||||
|
||||
Joy is intended as an effective vehicle for exploring this potential.
|
||||
|
||||
|
||||
## Speculative pre-evaluation
|
||||
|
||||
If you examine the traces of Joy programs it's easy to find places in the pending expression where some speculative interpreter could pre-compute results while the main interpreter was prosecuting the main "thread" of the program. For example consider (with the `.` indicating the current "location of the interpreter head" if you will, the split between the stack and the expression):
|
||||
|
||||
... a b c . F 2 3 + G H
|
||||
|
||||
The `2 3 +` between `F` and `G` is not at the interpreter "head" yet it is extremely unlikely that any function `F` will prevent it (eventually) being evaluated to `5`. We can imagine an interpreter that detects this sort of thing, evaluates the sub-expression with a different CPU, and "tags" the expression at `2` with the result `5`. If evaluation reaches `2` the interpreter can just use `5` without re-evaluating the whole sub-expression `2 3 +`.
|
||||
|
||||
This sort of thing happens all the time in Joy code.
|
||||
|
||||
For example, if you look at the appendix for the partial evaluation example there is a stage where we have this:
|
||||
|
||||
5 u u [1 >>] dipd [sqr] dip
|
||||
|
||||
Which can be written with the `dipdip` combinator:
|
||||
|
||||
5 u u [1 >>] [sqr] dipdip
|
||||
|
||||
Which then becomes this:
|
||||
|
||||
5 1 >> u sqr u
|
||||
|
||||
The interpreter could notice that `5 1 >>` and `u sqr` can proceed in parallel without interfering with each other. The `dipdip` combinator could be written to somehow hint to the interpreter that it should check for this posibility.
|
||||
|
||||
|
||||
## JIT
|
||||
|
||||
Whatever eventually winds up converting Joy code to machine code is susceptible to Just-in-Time compilation. For example, if you run Joypy on Pypy you take advantage of its JIT.
|
||||
|
||||
|
||||
# Joy as UI
|
||||
|
||||
|
||||
## Joy unifies CLI and GUI interfaces.
|
||||
|
||||
All Joy interaction consists of two basic actions:
|
||||
|
||||
1. Putting things onto the stack.
|
||||
2. Executing functions.
|
||||
|
||||
In a command-line setting you perform both of these actions the same way: entering Joy expressions as text. In a GUI you select items and copy or cut them to a user-visible stack (that is a first-class member of the UI, similar to the clipboard but with better visibility into contents and not restricted to one selection at a time.) You then trigger the evaluation of functions by clicking on buttons or menu items. *From the point-of-view of the underlying interpreter there is no difference between the input token streams for either UI modality.*
|
||||
|
||||
|
||||
## Simple and Comprehensible Model
|
||||
|
||||
In order to use their system(s) users must be able to easily and quickly develop a mental model of the system that maps to the actual system abstractions well enough to support the achievement of their goals.
|
||||
|
||||
(Arguably current systems are pretty poor at this. Even an abstraction as old and ubiquitous as "filesystem" is only incompletely understood by many computer users. Many people do not understand the difference between RAM and disk storage!)
|
||||
|
||||
The Joy model consists of just these main concepts:
|
||||
|
||||
1. A stack of values
|
||||
2. A dictionary of named commands
|
||||
3. An interpreter
|
||||
|
||||
Each of these is very simple and the first two even have real-world analogs (e.g. a *stack* of dishes or boxes or whatever, and, well, *dictionaries*.) It's easy to develop intuition for this system, resulting in a close match between the user's mental model and the actual system abstraction.
|
||||
|
||||
|
||||
# Joy as AST for multi-language interop
|
||||
|
||||
IR for Compilation
|
||||
|
||||
Cf. Graal & Truffle
|
||||
|
||||
"Software is eating the world"; Joy eats software.
|
||||
|
||||
Universal Solvent
|
||||
|
||||
Can write front-ends for translating other languages into Joy, thence to be refactored and fulminated into more efficient forms. "The Blob" of software.
|
||||
|
||||
|
||||
# Minimal Basis
|
||||
|
||||
Cf. SKI combinators, Peano arithmentic, Church numerals et. al.,
|
||||
|
||||
Folks have done work on figuring out the minimal set of combinators that are Turing-complete. Several of these sets are quite small.
|
||||
|
||||
Semantics can be defined in terms of Laws of Form for down-to-the-metal modeling of programs as logic circuits. Hardware description language.
|
||||
|
||||
|
||||
|
||||
# Math, Physics, Computation
|
||||
|
||||
Computational algorithms are used to communicate precisely
|
||||
some of the methods used in the analysis of dynamical phenomena.
|
||||
Expressing the methods of variational mechanics in a computer
|
||||
language forces them to be unambiguous and computationally
|
||||
effective. Computation requires us to be precise about the repre-
|
||||
sentation of mechanical and geometric notions as computational
|
||||
objects and permits us to represent explicitly the algorithms for
|
||||
manipulating these objects. Also, once formalized as a procedure,
|
||||
a mathematical idea becomes a tool that can be used directly to
|
||||
compute results.
|
||||
- "Structure and Interpretation of Classical Mechanics",
|
||||
Gerald Jay Sussman and Jack Wisdom with Meinhard E. Mayer
|
||||
|
||||
.
|
||||
|
||||
|
||||
|
||||
# Joy as glue language
|
||||
|
||||
Basically any existing code/programs can be exposed to Joy as a function or collection of functions.
|
||||
|
||||
## Shell command
|
||||
|
||||
Run a shell command.
|
||||
|
||||
"stdin" "cmd line" system
|
||||
-----------------------------------
|
||||
"stderr" "stdout" return_code
|
||||
|
||||
Then you can create e.g.:
|
||||
|
||||
foo == "awk {awk program}" system
|
||||
|
||||
Etc...
|
||||
|
||||
## Python libraries
|
||||
|
||||
## Ctypes (FFI) for loading binary libraries
|
||||
|
||||
|
||||
|
||||
|
||||
# Git as File Store
|
||||
|
||||
The old-fashioned File System abstraction is no longer justified. Joypy won't attempt to implement file and path operations. Instead there are a few functions that accept three args: a sha1 checksum of a blob of data, an initial index, and an offset. One function returns the string of data `blob[index:index+offset]`, while another accepts an additional quoted program and "runs it" with the data as the stack, for when you want to process a big ol' pile of data but don't want to load it into the interpreter. I imagine a use case for a third-party wrapped library that expects some sort of file or socket and streams over it somehow. Obviously, this is under-specified.
|
||||
|
||||
The sha1 checksum refers to data stored in some (global, universal) git repo, which is provided to the interpreter though some as-yet unimplemented meta-interpreter action.
|
||||
|
||||
**Git is a functional data type**, compatible with the semantic model of Joy. Implies shared datastore with obvious connection to git-archive & Datalad.
|
||||
|
||||
Functions over static data (Wikipedia dump; MRI data &c.) can be considered timeless (however much time their first evaluation takes) and cached/archived in the global shared git repo. (Large data in e.g. cloud & bittorrent, with meta-data in git-archive/Datalad)
|
||||
|
||||
Functions over streams (of possible mal-formed) data require a special stream-processing combinator and more care in their development. I haven't developed this in any detail, but it can be shown in many cases that e.g. a given function cannot grow unbounded (for all possible unbounded input streams.)
|
||||
|
||||
|
||||
|
||||
# Sympy Library
|
||||
|
||||
The mathematical functions in the Joypy library wrap the `math` module and other built-ins for the most part. It would be a simple matter to write wrapper functions for e.g. the Sympy packages' functions and provide symbolic math capabilities.
|
||||
|
||||
It would also be possible to make a dictionary that mapped the math functions to the Sympy versions. Evaluating Joy code with this dictionary (and a special stack with Sympy variables on it) would result in symbolic execution without rewriting the Joy code.
|
||||
|
||||
|
||||
|
||||
# Stack-based laguages as Dataflow
|
||||
|
||||
If the "places" in a stack are considered first-class entities and tracked through "stack chatter" operations (like `swap`) we can draw flow-lines for the data and represent the functions as boxes with input and output lines. Stack chatter becomes topological rearrangements of lines. The resulting structure is conceptually identical with *Dataflow* paradigm of programming.
|
||||
|
||||
(Related to this I suspect that all stack chatter disappears during compilation but I haven't nailed that down yet.)
|
||||
|
||||
I'm unable to find the original webpage that describe the above. :-(
|
||||
|
||||
|
||||
# Appendix Partial Evaluation Example
|
||||
|
||||
k u F
|
||||
-----------
|
||||
u^k
|
||||
|
||||
|
||||
k u 1 [popop 0 !=] [[popop odd][over *][]ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||
|
||||
F == 1 [popop 0 !=] [[popop odd][over *][]ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||
|
||||
5 u 1 [popop 0 !=] [[popop odd][over *][]ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||
|
||||
|
||||
5 u 1 popop 0 !=
|
||||
5 0 !=
|
||||
True
|
||||
|
||||
|
||||
5 u 1 [popop odd][over *][]ifte [1 >>] dipd [sqr] dip
|
||||
5 u 1 popop odd
|
||||
True
|
||||
|
||||
w/ sqr == dup *
|
||||
|
||||
5 u 1 over * [1 >>] dipd [sqr] dip
|
||||
5 u 1 u * [1 >>] dipd [sqr] dip
|
||||
5 u u [1 >>] dipd [sqr] dip
|
||||
5 1 >> u sqr u
|
||||
2 u_dup_* u
|
||||
--or--
|
||||
2 u_u_* u
|
||||
|
||||
2 u_u_* u popop 0 !=
|
||||
2 0 !=
|
||||
True
|
||||
|
||||
2 u_u_* u [popop odd][over *][]ifte [1 >>] dipd [sqr] dip
|
||||
...
|
||||
2 u_u_* u [1 >>] dipd [sqr] dip
|
||||
|
||||
2 1 >> u_u_* sqr u
|
||||
1 u_u_*_dup_* u
|
||||
|
||||
|
||||
1 u_u_*_dup_* u [popop odd][over *][]ifte [1 >>] dipd [sqr] dip
|
||||
1 u_u_*_dup_* u over * [1 >>] dipd [sqr] dip
|
||||
1 u_u_*_dup_* u u_u_*_dup_* * [1 >>] dipd [sqr] dip
|
||||
1 u_u_*_dup_* u_u_u_*_dup_*_* [1 >>] dipd [sqr] dip
|
||||
|
||||
1 1 >> u_u_*_dup_* sqr u_u_u_*_dup_*_*
|
||||
0 u_u_*_dup_* dup * u_u_u_*_dup_*_*
|
||||
0 u_u_*_dup_* u_u_*_dup_* * u_u_u_*_dup_*_*
|
||||
0 u_..._* u_u_u_*_dup_*_*
|
||||
|
||||
0 u_..._* u_u_u_*_dup_*_* [popop] dip
|
||||
|
||||
u_u_u_*_dup_*_*
|
||||
|
||||
^5 == dup dup * dup * *
|
||||
|
|
@ -1,508 +0,0 @@
|
|||
|
||||
# Using `x` to Generate Values
|
||||
|
||||
Cf. jp-reprod.html
|
||||
|
||||
|
||||
```python
|
||||
from notebook_preamble import J, V, define
|
||||
```
|
||||
|
||||
Consider the `x` combinator:
|
||||
|
||||
x == dup i
|
||||
|
||||
We can apply it to a quoted program consisting of some value `a` and some function `B`:
|
||||
|
||||
[a B] x
|
||||
[a B] a B
|
||||
|
||||
Let `B` function `swap` the `a` with the quote and run some function `C` on it to generate a new value `b`:
|
||||
|
||||
B == swap [C] dip
|
||||
|
||||
[a B] a B
|
||||
[a B] a swap [C] dip
|
||||
a [a B] [C] dip
|
||||
a C [a B]
|
||||
b [a B]
|
||||
|
||||
Now discard the quoted `a` with `rest` then `cons` `b`:
|
||||
|
||||
b [a B] rest cons
|
||||
b [B] cons
|
||||
[b B]
|
||||
|
||||
Altogether, this is the definition of `B`:
|
||||
|
||||
B == swap [C] dip rest cons
|
||||
|
||||
We can make a generator for the Natural numbers (0, 1, 2, ...) by using `0` for `a` and `[dup ++]` for `[C]`:
|
||||
|
||||
[0 swap [dup ++] dip rest cons]
|
||||
|
||||
Let's try it:
|
||||
|
||||
|
||||
```python
|
||||
V('[0 swap [dup ++] dip rest cons] x')
|
||||
```
|
||||
|
||||
. [0 swap [dup ++] dip rest cons] x
|
||||
[0 swap [dup ++] dip rest cons] . x
|
||||
[0 swap [dup ++] dip rest cons] . 0 swap [dup ++] dip rest cons
|
||||
[0 swap [dup ++] dip rest cons] 0 . swap [dup ++] dip rest cons
|
||||
0 [0 swap [dup ++] dip rest cons] . [dup ++] dip rest cons
|
||||
0 [0 swap [dup ++] dip rest cons] [dup ++] . dip rest cons
|
||||
0 . dup ++ [0 swap [dup ++] dip rest cons] rest cons
|
||||
0 0 . ++ [0 swap [dup ++] dip rest cons] rest cons
|
||||
0 1 . [0 swap [dup ++] dip rest cons] rest cons
|
||||
0 1 [0 swap [dup ++] dip rest cons] . rest cons
|
||||
0 1 [swap [dup ++] dip rest cons] . cons
|
||||
0 [1 swap [dup ++] dip rest cons] .
|
||||
|
||||
|
||||
After one application of `x` the quoted program contains `1` and `0` is below it on the stack.
|
||||
|
||||
|
||||
```python
|
||||
J('[0 swap [dup ++] dip rest cons] x x x x x pop')
|
||||
```
|
||||
|
||||
0 1 2 3 4
|
||||
|
||||
|
||||
## `direco`
|
||||
|
||||
|
||||
```python
|
||||
define('direco == dip rest cons')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
V('[0 swap [dup ++] direco] x')
|
||||
```
|
||||
|
||||
. [0 swap [dup ++] direco] x
|
||||
[0 swap [dup ++] direco] . x
|
||||
[0 swap [dup ++] direco] . 0 swap [dup ++] direco
|
||||
[0 swap [dup ++] direco] 0 . swap [dup ++] direco
|
||||
0 [0 swap [dup ++] direco] . [dup ++] direco
|
||||
0 [0 swap [dup ++] direco] [dup ++] . direco
|
||||
0 [0 swap [dup ++] direco] [dup ++] . dip rest cons
|
||||
0 . dup ++ [0 swap [dup ++] direco] rest cons
|
||||
0 0 . ++ [0 swap [dup ++] direco] rest cons
|
||||
0 1 . [0 swap [dup ++] direco] rest cons
|
||||
0 1 [0 swap [dup ++] direco] . rest cons
|
||||
0 1 [swap [dup ++] direco] . cons
|
||||
0 [1 swap [dup ++] direco] .
|
||||
|
||||
|
||||
## Making Generators
|
||||
We want to define a function that accepts `a` and `[C]` and builds our quoted program:
|
||||
|
||||
a [C] G
|
||||
-------------------------
|
||||
[a swap [C] direco]
|
||||
|
||||
Working in reverse:
|
||||
|
||||
[a swap [C] direco] cons
|
||||
a [swap [C] direco] concat
|
||||
a [swap] [[C] direco] swap
|
||||
a [[C] direco] [swap]
|
||||
a [C] [direco] cons [swap]
|
||||
|
||||
Reading from the bottom up:
|
||||
|
||||
G == [direco] cons [swap] swap concat cons
|
||||
G == [direco] cons [swap] swoncat cons
|
||||
|
||||
|
||||
```python
|
||||
define('G == [direco] cons [swap] swoncat cons')
|
||||
```
|
||||
|
||||
Let's try it out:
|
||||
|
||||
|
||||
```python
|
||||
J('0 [dup ++] G')
|
||||
```
|
||||
|
||||
[0 swap [dup ++] direco]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('0 [dup ++] G x x x pop')
|
||||
```
|
||||
|
||||
0 1 2
|
||||
|
||||
|
||||
### Powers of 2
|
||||
|
||||
|
||||
```python
|
||||
J('1 [dup 1 <<] G x x x x x x x x x pop')
|
||||
```
|
||||
|
||||
1 2 4 8 16 32 64 128 256
|
||||
|
||||
|
||||
### `[x] times`
|
||||
If we have one of these quoted programs we can drive it using `times` with the `x` combinator.
|
||||
|
||||
|
||||
```python
|
||||
J('23 [dup ++] G 5 [x] times')
|
||||
```
|
||||
|
||||
23 24 25 26 27 [28 swap [dup ++] direco]
|
||||
|
||||
|
||||
## Generating Multiples of Three and Five
|
||||
Look at the treatment of the Project Euler Problem One in the "Developing a Program" notebook and you'll see that we might be interested in generating an endless cycle of:
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
|
||||
To do this we want to encode the numbers as pairs of bits in a single int:
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
0b 11 10 01 11 01 10 11 == 14811
|
||||
|
||||
And pick them off by masking with 3 (binary 11) and then shifting the int right two bits.
|
||||
|
||||
|
||||
```python
|
||||
define('PE1.1 == dup [3 &] dip 2 >>')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
V('14811 PE1.1')
|
||||
```
|
||||
|
||||
. 14811 PE1.1
|
||||
14811 . PE1.1
|
||||
14811 . dup [3 &] dip 2 >>
|
||||
14811 14811 . [3 &] dip 2 >>
|
||||
14811 14811 [3 &] . dip 2 >>
|
||||
14811 . 3 & 14811 2 >>
|
||||
14811 3 . & 14811 2 >>
|
||||
3 . 14811 2 >>
|
||||
3 14811 . 2 >>
|
||||
3 14811 2 . >>
|
||||
3 3702 .
|
||||
|
||||
|
||||
If we plug `14811` and `[PE1.1]` into our generator form...
|
||||
|
||||
|
||||
```python
|
||||
J('14811 [PE1.1] G')
|
||||
```
|
||||
|
||||
[14811 swap [PE1.1] direco]
|
||||
|
||||
|
||||
...we get a generator that works for seven cycles before it reaches zero:
|
||||
|
||||
|
||||
```python
|
||||
J('[14811 swap [PE1.1] direco] 7 [x] times')
|
||||
```
|
||||
|
||||
3 2 1 3 1 2 3 [0 swap [PE1.1] direco]
|
||||
|
||||
|
||||
### Reset at Zero
|
||||
We need a function that checks if the int has reached zero and resets it if so.
|
||||
|
||||
|
||||
```python
|
||||
define('PE1.1.check == dup [pop 14811] [] branch')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('14811 [PE1.1.check PE1.1] G')
|
||||
```
|
||||
|
||||
[14811 swap [PE1.1.check PE1.1] direco]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[14811 swap [PE1.1.check PE1.1] direco] 21 [x] times')
|
||||
```
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 [0 swap [PE1.1.check PE1.1] direco]
|
||||
|
||||
|
||||
(It would be more efficient to reset the int every seven cycles but that's a little beyond the scope of this article. This solution does extra work, but not much, and we're not using it "in production" as they say.)
|
||||
|
||||
### Run 466 times
|
||||
In the PE1 problem we are asked to sum all the multiples of three and five less than 1000. It's worked out that we need to use all seven numbers sixty-six times and then four more.
|
||||
|
||||
|
||||
```python
|
||||
J('7 66 * 4 +')
|
||||
```
|
||||
|
||||
466
|
||||
|
||||
|
||||
If we drive our generator 466 times and sum the stack we get 999.
|
||||
|
||||
|
||||
```python
|
||||
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times')
|
||||
```
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 [57 swap [PE1.1.check PE1.1] direco]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times pop enstacken sum')
|
||||
```
|
||||
|
||||
999
|
||||
|
||||
|
||||
## Project Euler Problem One
|
||||
|
||||
|
||||
```python
|
||||
define('PE1.2 == + dup [+] dip')
|
||||
```
|
||||
|
||||
Now we can add `PE1.2` to the quoted program given to `G`.
|
||||
|
||||
|
||||
```python
|
||||
J('0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop')
|
||||
```
|
||||
|
||||
233168
|
||||
|
||||
|
||||
## A generator for the Fibonacci Sequence.
|
||||
Consider:
|
||||
|
||||
[b a F] x
|
||||
[b a F] b a F
|
||||
|
||||
The obvious first thing to do is just add `b` and `a`:
|
||||
|
||||
[b a F] b a +
|
||||
[b a F] b+a
|
||||
|
||||
From here we want to arrive at:
|
||||
|
||||
b [b+a b F]
|
||||
|
||||
Let's start with `swons`:
|
||||
|
||||
[b a F] b+a swons
|
||||
[b+a b a F]
|
||||
|
||||
Considering this quote as a stack:
|
||||
|
||||
F a b b+a
|
||||
|
||||
We want to get it to:
|
||||
|
||||
F b b+a b
|
||||
|
||||
So:
|
||||
|
||||
F a b b+a popdd over
|
||||
F b b+a b
|
||||
|
||||
And therefore:
|
||||
|
||||
[b+a b a F] [popdd over] infra
|
||||
[b b+a b F]
|
||||
|
||||
But we can just use `cons` to carry `b+a` into the quote:
|
||||
|
||||
[b a F] b+a [popdd over] cons infra
|
||||
[b a F] [b+a popdd over] infra
|
||||
[b b+a b F]
|
||||
|
||||
Lastly:
|
||||
|
||||
[b b+a b F] uncons
|
||||
b [b+a b F]
|
||||
|
||||
Putting it all together:
|
||||
|
||||
F == + [popdd over] cons infra uncons
|
||||
fib_gen == [1 1 F]
|
||||
|
||||
|
||||
```python
|
||||
define('fib == + [popdd over] cons infra uncons')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
define('fib_gen == [1 1 fib]')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('fib_gen 10 [x] times')
|
||||
```
|
||||
|
||||
1 2 3 5 8 13 21 34 55 89 [144 89 fib]
|
||||
|
||||
|
||||
## Project Euler Problem Two
|
||||
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
|
||||
find the sum of the even-valued terms.
|
||||
|
||||
Now that we have a generator for the Fibonacci sequence, we need a function that adds a term in the sequence to a sum if it is even, and `pop`s it otherwise.
|
||||
|
||||
|
||||
```python
|
||||
define('PE2.1 == dup 2 % [+] [pop] branch')
|
||||
```
|
||||
|
||||
And a predicate function that detects when the terms in the series "exceed four million".
|
||||
|
||||
|
||||
```python
|
||||
define('>4M == 4000000 >')
|
||||
```
|
||||
|
||||
Now it's straightforward to define `PE2` as a recursive function that generates terms in the Fibonacci sequence until they exceed four million and sums the even ones.
|
||||
|
||||
|
||||
```python
|
||||
define('PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('PE2')
|
||||
```
|
||||
|
||||
4613732
|
||||
|
||||
|
||||
Here's the collected program definitions:
|
||||
|
||||
fib == + swons [popdd over] infra uncons
|
||||
fib_gen == [1 1 fib]
|
||||
|
||||
even == dup 2 %
|
||||
>4M == 4000000 >
|
||||
|
||||
PE2.1 == even [+] [pop] branch
|
||||
PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec
|
||||
|
||||
### Even-valued Fibonacci Terms
|
||||
|
||||
Using `o` for odd and `e` for even:
|
||||
|
||||
o + o = e
|
||||
e + e = e
|
||||
o + e = o
|
||||
|
||||
So the Fibonacci sequence considered in terms of just parity would be:
|
||||
|
||||
o o e o o e o o e o o e o o e o o e
|
||||
1 1 2 3 5 8 . . .
|
||||
|
||||
Every third term is even.
|
||||
|
||||
|
||||
|
||||
```python
|
||||
J('[1 0 fib] x x x') # To start the sequence with 1 1 2 3 instead of 1 2 3.
|
||||
```
|
||||
|
||||
1 1 2 [3 2 fib]
|
||||
|
||||
|
||||
Drive the generator three times and `popop` the two odd terms.
|
||||
|
||||
|
||||
```python
|
||||
J('[1 0 fib] x x x [popop] dipd')
|
||||
```
|
||||
|
||||
2 [3 2 fib]
|
||||
|
||||
|
||||
|
||||
```python
|
||||
define('PE2.2 == x x x [popop] dipd')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('[1 0 fib] 10 [PE2.2] times')
|
||||
```
|
||||
|
||||
2 8 34 144 610 2584 10946 46368 196418 832040 [1346269 832040 fib]
|
||||
|
||||
|
||||
Replace `x` with our new driver function `PE2.2` and start our `fib` generator at `1 0`.
|
||||
|
||||
|
||||
```python
|
||||
J('0 [1 0 fib] PE2.2 [pop >4M] [popop] [[PE2.1] dip PE2.2] primrec')
|
||||
```
|
||||
|
||||
4613732
|
||||
|
||||
|
||||
## How to compile these?
|
||||
You would probably start with a special version of `G`, and perhaps modifications to the default `x`?
|
||||
|
||||
## An Interesting Variation
|
||||
|
||||
|
||||
```python
|
||||
define('codireco == cons dip rest cons')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
V('[0 [dup ++] codireco] x')
|
||||
```
|
||||
|
||||
. [0 [dup ++] codireco] x
|
||||
[0 [dup ++] codireco] . x
|
||||
[0 [dup ++] codireco] . 0 [dup ++] codireco
|
||||
[0 [dup ++] codireco] 0 . [dup ++] codireco
|
||||
[0 [dup ++] codireco] 0 [dup ++] . codireco
|
||||
[0 [dup ++] codireco] 0 [dup ++] . cons dip rest cons
|
||||
[0 [dup ++] codireco] [0 dup ++] . dip rest cons
|
||||
. 0 dup ++ [0 [dup ++] codireco] rest cons
|
||||
0 . dup ++ [0 [dup ++] codireco] rest cons
|
||||
0 0 . ++ [0 [dup ++] codireco] rest cons
|
||||
0 1 . [0 [dup ++] codireco] rest cons
|
||||
0 1 [0 [dup ++] codireco] . rest cons
|
||||
0 1 [[dup ++] codireco] . cons
|
||||
0 [1 [dup ++] codireco] .
|
||||
|
||||
|
||||
|
||||
```python
|
||||
define('G == [codireco] cons cons')
|
||||
```
|
||||
|
||||
|
||||
```python
|
||||
J('230 [dup ++] G 5 [x] times pop')
|
||||
```
|
||||
|
||||
230 231 232 233 234
|
||||
|
||||
|
|
@ -1,639 +0,0 @@
|
|||
|
||||
Using ``x`` to Generate Values
|
||||
==============================
|
||||
|
||||
Cf. jp-reprod.html
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
from notebook_preamble import J, V, define
|
||||
|
||||
Consider the ``x`` combinator:
|
||||
|
||||
::
|
||||
|
||||
x == dup i
|
||||
|
||||
We can apply it to a quoted program consisting of some value ``a`` and
|
||||
some function ``B``:
|
||||
|
||||
::
|
||||
|
||||
[a B] x
|
||||
[a B] a B
|
||||
|
||||
Let ``B`` function ``swap`` the ``a`` with the quote and run some
|
||||
function ``C`` on it to generate a new value ``b``:
|
||||
|
||||
::
|
||||
|
||||
B == swap [C] dip
|
||||
|
||||
[a B] a B
|
||||
[a B] a swap [C] dip
|
||||
a [a B] [C] dip
|
||||
a C [a B]
|
||||
b [a B]
|
||||
|
||||
Now discard the quoted ``a`` with ``rest`` then ``cons`` ``b``:
|
||||
|
||||
::
|
||||
|
||||
b [a B] rest cons
|
||||
b [B] cons
|
||||
[b B]
|
||||
|
||||
Altogether, this is the definition of ``B``:
|
||||
|
||||
::
|
||||
|
||||
B == swap [C] dip rest cons
|
||||
|
||||
We can make a generator for the Natural numbers (0, 1, 2, ...) by using
|
||||
``0`` for ``a`` and ``[dup ++]`` for ``[C]``:
|
||||
|
||||
::
|
||||
|
||||
[0 swap [dup ++] dip rest cons]
|
||||
|
||||
Let's try it:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('[0 swap [dup ++] dip rest cons] x')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. [0 swap [dup ++] dip rest cons] x
|
||||
[0 swap [dup ++] dip rest cons] . x
|
||||
[0 swap [dup ++] dip rest cons] . 0 swap [dup ++] dip rest cons
|
||||
[0 swap [dup ++] dip rest cons] 0 . swap [dup ++] dip rest cons
|
||||
0 [0 swap [dup ++] dip rest cons] . [dup ++] dip rest cons
|
||||
0 [0 swap [dup ++] dip rest cons] [dup ++] . dip rest cons
|
||||
0 . dup ++ [0 swap [dup ++] dip rest cons] rest cons
|
||||
0 0 . ++ [0 swap [dup ++] dip rest cons] rest cons
|
||||
0 1 . [0 swap [dup ++] dip rest cons] rest cons
|
||||
0 1 [0 swap [dup ++] dip rest cons] . rest cons
|
||||
0 1 [swap [dup ++] dip rest cons] . cons
|
||||
0 [1 swap [dup ++] dip rest cons] .
|
||||
|
||||
|
||||
After one application of ``x`` the quoted program contains ``1`` and
|
||||
``0`` is below it on the stack.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[0 swap [dup ++] dip rest cons] x x x x x pop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
0 1 2 3 4
|
||||
|
||||
|
||||
``direco``
|
||||
----------
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('direco == dip rest cons')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('[0 swap [dup ++] direco] x')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. [0 swap [dup ++] direco] x
|
||||
[0 swap [dup ++] direco] . x
|
||||
[0 swap [dup ++] direco] . 0 swap [dup ++] direco
|
||||
[0 swap [dup ++] direco] 0 . swap [dup ++] direco
|
||||
0 [0 swap [dup ++] direco] . [dup ++] direco
|
||||
0 [0 swap [dup ++] direco] [dup ++] . direco
|
||||
0 [0 swap [dup ++] direco] [dup ++] . dip rest cons
|
||||
0 . dup ++ [0 swap [dup ++] direco] rest cons
|
||||
0 0 . ++ [0 swap [dup ++] direco] rest cons
|
||||
0 1 . [0 swap [dup ++] direco] rest cons
|
||||
0 1 [0 swap [dup ++] direco] . rest cons
|
||||
0 1 [swap [dup ++] direco] . cons
|
||||
0 [1 swap [dup ++] direco] .
|
||||
|
||||
|
||||
Making Generators
|
||||
-----------------
|
||||
|
||||
We want to define a function that accepts ``a`` and ``[C]`` and builds
|
||||
our quoted program:
|
||||
|
||||
::
|
||||
|
||||
a [C] G
|
||||
-------------------------
|
||||
[a swap [C] direco]
|
||||
|
||||
Working in reverse:
|
||||
|
||||
::
|
||||
|
||||
[a swap [C] direco] cons
|
||||
a [swap [C] direco] concat
|
||||
a [swap] [[C] direco] swap
|
||||
a [[C] direco] [swap]
|
||||
a [C] [direco] cons [swap]
|
||||
|
||||
Reading from the bottom up:
|
||||
|
||||
::
|
||||
|
||||
G == [direco] cons [swap] swap concat cons
|
||||
G == [direco] cons [swap] swoncat cons
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('G == [direco] cons [swap] swoncat cons')
|
||||
|
||||
Let's try it out:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('0 [dup ++] G')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[0 swap [dup ++] direco]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('0 [dup ++] G x x x pop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
0 1 2
|
||||
|
||||
|
||||
Powers of 2
|
||||
~~~~~~~~~~~
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('1 [dup 1 <<] G x x x x x x x x x pop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
1 2 4 8 16 32 64 128 256
|
||||
|
||||
|
||||
``[x] times``
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
If we have one of these quoted programs we can drive it using ``times``
|
||||
with the ``x`` combinator.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('23 [dup ++] G 5 [x] times')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
23 24 25 26 27 [28 swap [dup ++] direco]
|
||||
|
||||
|
||||
Generating Multiples of Three and Five
|
||||
--------------------------------------
|
||||
|
||||
Look at the treatment of the Project Euler Problem One in the
|
||||
"Developing a Program" notebook and you'll see that we might be
|
||||
interested in generating an endless cycle of:
|
||||
|
||||
::
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
|
||||
To do this we want to encode the numbers as pairs of bits in a single
|
||||
int:
|
||||
|
||||
::
|
||||
|
||||
3 2 1 3 1 2 3
|
||||
0b 11 10 01 11 01 10 11 == 14811
|
||||
|
||||
And pick them off by masking with 3 (binary 11) and then shifting the
|
||||
int right two bits.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1.1 == dup [3 &] dip 2 >>')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('14811 PE1.1')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. 14811 PE1.1
|
||||
14811 . PE1.1
|
||||
14811 . dup [3 &] dip 2 >>
|
||||
14811 14811 . [3 &] dip 2 >>
|
||||
14811 14811 [3 &] . dip 2 >>
|
||||
14811 . 3 & 14811 2 >>
|
||||
14811 3 . & 14811 2 >>
|
||||
3 . 14811 2 >>
|
||||
3 14811 . 2 >>
|
||||
3 14811 2 . >>
|
||||
3 3702 .
|
||||
|
||||
|
||||
If we plug ``14811`` and ``[PE1.1]`` into our generator form...
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('14811 [PE1.1] G')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[14811 swap [PE1.1] direco]
|
||||
|
||||
|
||||
...we get a generator that works for seven cycles before it reaches
|
||||
zero:
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[14811 swap [PE1.1] direco] 7 [x] times')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3 2 1 3 1 2 3 [0 swap [PE1.1] direco]
|
||||
|
||||
|
||||
Reset at Zero
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
We need a function that checks if the int has reached zero and resets it
|
||||
if so.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1.1.check == dup [pop 14811] [] branch')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('14811 [PE1.1.check PE1.1] G')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
[14811 swap [PE1.1.check PE1.1] direco]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[14811 swap [PE1.1.check PE1.1] direco] 21 [x] times')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 [0 swap [PE1.1.check PE1.1] direco]
|
||||
|
||||
|
||||
(It would be more efficient to reset the int every seven cycles but
|
||||
that's a little beyond the scope of this article. This solution does
|
||||
extra work, but not much, and we're not using it "in production" as they
|
||||
say.)
|
||||
|
||||
Run 466 times
|
||||
~~~~~~~~~~~~~
|
||||
|
||||
In the PE1 problem we are asked to sum all the multiples of three and
|
||||
five less than 1000. It's worked out that we need to use all seven
|
||||
numbers sixty-six times and then four more.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('7 66 * 4 +')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
466
|
||||
|
||||
|
||||
If we drive our generator 466 times and sum the stack we get 999.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 1 2 3 3 2 1 3 [57 swap [PE1.1.check PE1.1] direco]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[14811 swap [PE1.1.check PE1.1] direco] 466 [x] times pop enstacken sum')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
999
|
||||
|
||||
|
||||
Project Euler Problem One
|
||||
-------------------------
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE1.2 == + dup [+] dip')
|
||||
|
||||
Now we can add ``PE1.2`` to the quoted program given to ``G``.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
233168
|
||||
|
||||
|
||||
A generator for the Fibonacci Sequence.
|
||||
---------------------------------------
|
||||
|
||||
Consider:
|
||||
|
||||
::
|
||||
|
||||
[b a F] x
|
||||
[b a F] b a F
|
||||
|
||||
The obvious first thing to do is just add ``b`` and ``a``:
|
||||
|
||||
::
|
||||
|
||||
[b a F] b a +
|
||||
[b a F] b+a
|
||||
|
||||
From here we want to arrive at:
|
||||
|
||||
::
|
||||
|
||||
b [b+a b F]
|
||||
|
||||
Let's start with ``swons``:
|
||||
|
||||
::
|
||||
|
||||
[b a F] b+a swons
|
||||
[b+a b a F]
|
||||
|
||||
Considering this quote as a stack:
|
||||
|
||||
::
|
||||
|
||||
F a b b+a
|
||||
|
||||
We want to get it to:
|
||||
|
||||
::
|
||||
|
||||
F b b+a b
|
||||
|
||||
So:
|
||||
|
||||
::
|
||||
|
||||
F a b b+a popdd over
|
||||
F b b+a b
|
||||
|
||||
And therefore:
|
||||
|
||||
::
|
||||
|
||||
[b+a b a F] [popdd over] infra
|
||||
[b b+a b F]
|
||||
|
||||
But we can just use ``cons`` to carry ``b+a`` into the quote:
|
||||
|
||||
::
|
||||
|
||||
[b a F] b+a [popdd over] cons infra
|
||||
[b a F] [b+a popdd over] infra
|
||||
[b b+a b F]
|
||||
|
||||
Lastly:
|
||||
|
||||
::
|
||||
|
||||
[b b+a b F] uncons
|
||||
b [b+a b F]
|
||||
|
||||
Putting it all together:
|
||||
|
||||
::
|
||||
|
||||
F == + [popdd over] cons infra uncons
|
||||
fib_gen == [1 1 F]
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('fib == + [popdd over] cons infra uncons')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('fib_gen == [1 1 fib]')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('fib_gen 10 [x] times')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
1 2 3 5 8 13 21 34 55 89 [144 89 fib]
|
||||
|
||||
|
||||
Project Euler Problem Two
|
||||
-------------------------
|
||||
|
||||
::
|
||||
|
||||
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
|
||||
find the sum of the even-valued terms.
|
||||
|
||||
Now that we have a generator for the Fibonacci sequence, we need a
|
||||
function that adds a term in the sequence to a sum if it is even, and
|
||||
``pop``\ s it otherwise.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE2.1 == dup 2 % [+] [pop] branch')
|
||||
|
||||
And a predicate function that detects when the terms in the series
|
||||
"exceed four million".
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('>4M == 4000000 >')
|
||||
|
||||
Now it's straightforward to define ``PE2`` as a recursive function that
|
||||
generates terms in the Fibonacci sequence until they exceed four million
|
||||
and sums the even ones.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('PE2')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
4613732
|
||||
|
||||
|
||||
Here's the collected program definitions:
|
||||
|
||||
::
|
||||
|
||||
fib == + swons [popdd over] infra uncons
|
||||
fib_gen == [1 1 fib]
|
||||
|
||||
even == dup 2 %
|
||||
>4M == 4000000 >
|
||||
|
||||
PE2.1 == even [+] [pop] branch
|
||||
PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec
|
||||
|
||||
Even-valued Fibonacci Terms
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Using ``o`` for odd and ``e`` for even:
|
||||
|
||||
::
|
||||
|
||||
o + o = e
|
||||
e + e = e
|
||||
o + e = o
|
||||
|
||||
So the Fibonacci sequence considered in terms of just parity would be:
|
||||
|
||||
::
|
||||
|
||||
o o e o o e o o e o o e o o e o o e
|
||||
1 1 2 3 5 8 . . .
|
||||
|
||||
Every third term is even.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 0 fib] x x x') # To start the sequence with 1 1 2 3 instead of 1 2 3.
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
1 1 2 [3 2 fib]
|
||||
|
||||
|
||||
Drive the generator three times and ``popop`` the two odd terms.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 0 fib] x x x [popop] dipd')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2 [3 2 fib]
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('PE2.2 == x x x [popop] dipd')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('[1 0 fib] 10 [PE2.2] times')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
2 8 34 144 610 2584 10946 46368 196418 832040 [1346269 832040 fib]
|
||||
|
||||
|
||||
Replace ``x`` with our new driver function ``PE2.2`` and start our
|
||||
``fib`` generator at ``1 0``.
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('0 [1 0 fib] PE2.2 [pop >4M] [popop] [[PE2.1] dip PE2.2] primrec')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
4613732
|
||||
|
||||
|
||||
How to compile these?
|
||||
---------------------
|
||||
|
||||
You would probably start with a special version of ``G``, and perhaps
|
||||
modifications to the default ``x``?
|
||||
|
||||
An Interesting Variation
|
||||
------------------------
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('codireco == cons dip rest cons')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
V('[0 [dup ++] codireco] x')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
. [0 [dup ++] codireco] x
|
||||
[0 [dup ++] codireco] . x
|
||||
[0 [dup ++] codireco] . 0 [dup ++] codireco
|
||||
[0 [dup ++] codireco] 0 . [dup ++] codireco
|
||||
[0 [dup ++] codireco] 0 [dup ++] . codireco
|
||||
[0 [dup ++] codireco] 0 [dup ++] . cons dip rest cons
|
||||
[0 [dup ++] codireco] [0 dup ++] . dip rest cons
|
||||
. 0 dup ++ [0 [dup ++] codireco] rest cons
|
||||
0 . dup ++ [0 [dup ++] codireco] rest cons
|
||||
0 0 . ++ [0 [dup ++] codireco] rest cons
|
||||
0 1 . [0 [dup ++] codireco] rest cons
|
||||
0 1 [0 [dup ++] codireco] . rest cons
|
||||
0 1 [[dup ++] codireco] . cons
|
||||
0 [1 [dup ++] codireco] .
|
||||
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
define('G == [codireco] cons cons')
|
||||
|
||||
.. code:: ipython2
|
||||
|
||||
J('230 [dup ++] G 5 [x] times pop')
|
||||
|
||||
|
||||
.. parsed-literal::
|
||||
|
||||
230 231 232 233 234
|
||||
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
# Some Jupyter Notebooks and other material.
|
||||
|
||||
All of the notebooks are also available as HTML and Markdown files (generated using nbconvert) so you can view them without running Jupyter.
|
||||
|
||||
In order to run the [Jupyter Notebooks](https://jupyter.org/index.html) you need Jupyter (obviously) and you should install `Joypy`. Here's an example using `virtualenv` from the `joypy/` directory:
|
||||
|
||||
virtualenv --system-site-packages <DIRNAME>
|
||||
. ./<DIRNAME>/bin/activate
|
||||
python ./setup.py install
|
||||
|
||||
Once that's done you should be able to start Jupyter Notebook server with, e.g.:
|
||||
|
||||
python -n notebook
|
||||
|
||||
This starts it using the `virtualenv` version of Python so `joy` will be available. Navigate to the `joypy/docs` directory and the notebooks should be able to import the `notebook_preamble.py` file.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- 1. Basic Use of Joy in a Notebook
|
||||
- 2. Library Examples - Short examples of each word in the dictionary. Various formats.
|
||||
- 3. Developing a Program - Working with the first problem from Project Euler, "Find the sum of all the multiples of 3 or 5 below 1000", several forms of the program are derived.
|
||||
- 4. Replacing Functions in the Dictionary - Shows the basics of defining new "primitive" functions in Python or as definitions and adding them to the dictionary.
|
||||
- Factorial Function and Paramorphisms - A basic pattern of recursive control-flow.
|
||||
- Generator Programs - Using the x combinator to make generator programs which can be used to create unbounded streams of values.
|
||||
- Hylo-, Ana-, Cata-morphisms - Some basic patterns of recursive control-flow structures.
|
||||
- Quadratic - Not-so-annoying Quadratic Formula.
|
||||
- Trees - Ordered Binary Trees in Joy and more recursion.
|
||||
- Zipper - A preliminary examination of the idea of data-structure "zippers" for traversing datastructures.
|
||||
- notebook_preamble.py - Imported into notebooks to simplify the preamble code.
|
||||
- pe1.py pe1.txt - Set up and execute a Joy program for the first problem from Project Euler. The pe1.txt file is the trace. It's 2.8M uncompressed. Compressed with gzip it becomes just 0.12M.
|
||||
- repl.py - Run this script to start a REPL. Useful for e.g. running Joy code in a debugger.
|
||||
|
||||
## Notes
|
||||
|
||||
One of the things that interests me about Joy is how programming becomes
|
||||
less about writing code and more about sound reasoning about simple
|
||||
(almost geometric) programs. Many of the notebooks in this collection
|
||||
consist of several pages of discussion to arrive at a few lines of Joy
|
||||
definitions. I think this is a good thing. This is "literate
|
||||
programming". The "programs" resemble mathematical proofs. You aren't
|
||||
implementing so much as deriving. The structure of Joy seems to force
|
||||
you to think clearly about the task in a way that is reliable but
|
||||
extremely flexible. It feels like a puzzle game, and the puzzles are
|
||||
often simple, and the solutions build on each other.
|
||||