Combinator Reduction Wolfram Mathematica - math

How can I implement the normal reduction strategy for Combinators {S,K,I} in Mathematica?
Here are the rules:
S[x][y][z]->x[y][z[y]]
K[x][y][z]->x
Also we have an Y combinator ( fixed point) thus Y[a]=a[Ya]].
And we must "evaluate" the expression like ,for instance, S[K][K][a] = K[a][K[a]]=a
It is highly important to have a ONE step of reduction. Thus, that the result will be in application one step many times..
Thanks in anticipation for any suggestions!!!

Let's define a function called eval that will perform one step of combinator evaluation. First, we need to consider what exactly constitutes a single step. Arbitrarily, we will evaluate the left-outermost expression first and work inwards from there.
ClearAll[eval]
eval[e_] := Module[{r = eval1[e]}, r /; r =!= e]
eval[e:f_[g_]] := Module[{r = eval[f][g]}, r /; r =!= e]
eval[e:f_[g_]] := Module[{r = f[eval[g]]}, r /; r =!= e]
eval[e_] := e
Note that the rules are only applied if they actually change the expression. The awkwardness of these definitions is due to Mathematica's lack of a pattern expression that will match arbitrarily long curried argument lists.
Now we can define the recognized combinators, S, K and I:
ClearAll[eval1]
eval1[s[f_][g_][h_]] := f[h][g[h]]
eval1[k[f_][_]] := f
eval1[i[f_]] := f
The symbols are in lower case here mainly to avoid the way that Mathematica renders the built-in symbol I, the imaginary unit.
Any other combinators will be taken as variables and left unevaluated:
eval1[e_] := e
Now we can try out the basic cases:
i[f] // eval
(* f *)
k[f][g] // eval
(* f *)
s[f][g][h] // eval
(* f[h][g[h]] *)
For more interesting cases, let's define evalAll that shows all steps in an evaluation chain:
ClearAll[evalAll]
evalAll[e_, n_:Infinity] := FixedPointList[eval, e, n+1] // Most // Column
s[k][k][a] // evalAll
(*
s[k][k][a]
k[a][k[a]]
a
*)
s[s[m][n][r]][k[a][b]][c] // evalAll
(*
s[s[m][n][r]][k[a][b]][c]
s[m][n][r][c][k[a][b][c]]
m[r][n[r]][c][k[a][b][c]]
m[r][n[r]][c][a[c]]
*)
f[s[i[k]][k][g][i[f]]] // evalAll
(*
f[s[i[k]][k][g][i[f]]]
f[i[k][g][k[g]][i[f]]]
f[k[g][k[g]][i[f]]]
f[g[i[f]]]
f[g[f]]
*)
evalAll takes an optional "count" argument to limit the number of steps shown. This is useful for divergent expressions -- like a direct expression of the Y combinator:
eval1[y[f_]] := f[y[f]]
y[f] // evalAll[#, 4]&
(*
y[f]
f[y[f]]
f[f[y[f]]]
f[f[f[y[f]]]]
f[f[f[f[y[f]]]]]
*)
... but it is more fun to express such sequences in terms of SKI:
Module[{y = s[k[s[i][i]]][s[s[k[s]][k]][k[s[i][i]]]]}
, evalAll[y[f], 28]
]
(*
s[k[s[i][i]]][s[s[k[s]][k]][k[s[i][i]]]][f]
k[s[i][i]][f][s[s[k[s]][k]][k[s[i][i]]][f]]
s[i][i][s[s[k[s]][k]][k[s[i][i]]][f]]
i[s[s[k[s]][k]][k[s[i][i]]][f]][i[s[s[k[s]][k]][k[s[i][i]]][f]]]
s[s[k[s]][k]][k[s[i][i]]][f][i[s[s[k[s]][k]][k[s[i][i]]][f]]]
s[k[s]][k][f][k[s[i][i]][f]][i[s[s[k[s]][k]][k[s[i][i]]][f]]]
k[s][f][k[f]][k[s[i][i]][f]][i[s[s[k[s]][k]][k[s[i][i]]][f]]]
s[k[f]][k[s[i][i]][f]][i[s[s[k[s]][k]][k[s[i][i]]][f]]]
k[f][i[s[s[k[s]][k]][k[s[i][i]]][f]]][k[s[i][i]][f][i[s[s[k[s]][k]][k[s[i][i]]][f]]]]
f[k[s[i][i]][f][i[s[s[k[s]][k]][k[s[i][i]]][f]]]] <-- f[...]
f[s[i][i][i[s[s[k[s]][k]][k[s[i][i]]][f]]]]
f[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]
f[i[s[s[k[s]][k]][k[s[i][i]]][f]][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]
f[s[s[k[s]][k]][k[s[i][i]]][f][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]
f[s[k[s]][k][f][k[s[i][i]][f]][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]
f[k[s][f][k[f]][k[s[i][i]][f]][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]
f[s[k[f]][k[s[i][i]][f]][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]
f[k[f][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]][k[s[i][i]][f][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]
f[f[k[s[i][i]][f][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]] <-- f[f[...]]
f[f[s[i][i][i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]
f[f[i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]
f[f[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]
f[f[i[s[s[k[s]][k]][k[s[i][i]]][f]][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]
f[f[s[s[k[s]][k]][k[s[i][i]]][f][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]
f[f[s[k[s]][k][f][k[s[i][i]][f]][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]
f[f[k[s][f][k[f]][k[s[i][i]][f]][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]
f[f[s[k[f]][k[s[i][i]][f]][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]
f[f[k[f][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]][k[s[i][i]][f][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]]
f[f[f[k[s[i][i]][f][i[i[i[s[s[k[s]][k]][k[s[i][i]]][f]]]]]]]] <-- f[f[f[...]]]
*)

Related

imperative to functional: n-body collision

I'm a beginner in functional programming but I'm famaliar with imperative programming. I'm having trouble translating a piece of cpp code involving updatating two objects at the same time (context is n-body simulation).
It's roughly like this in c++:
for (Particle &i: particles) {
for (Particle &j: particles) {
collide(i, j) // function that mutates particles i and j
}
}
I'm translating this to Ocaml, with immutable objects and immutable Lists. The difficult part is that I need to replace two objects at the same time. So far I have this:
List.map (fun i ->
List.map (fun j ->
let (new_i, new_j) = collide(i, j) in // function that returns new particles i, j
// how do i update particles with new i, j?
) particles
) particles
How do I replace both objects in the List at the same time?
The functional equivalent of the imperative code is just as simple as,
let nbody f xs =
List.map (fun x -> List.fold_left f x xs) xs
It is a bit more generic, as a I abstracted the collide function and made it a parameter. The function f takes two bodies and returns the state of the first body as affected by the second body. For example, we can implement the following symbolic collide function,
let symbolic x y = "f(" ^ x ^ "," ^ y ^ ")"
so that we can see the result and associativity of the the collide function application,
# nbody symbolic [
"x"; "y"; "z"
];;
- : string list =
["f(f(f(x,x),y),z)"; "f(f(f(y,x),y),z)"; "f(f(f(z,x),y),z)"]
So, the first element of the output list is the result of collision of x with x itself, then with y, then with z. The second element is the result of collision of y with x, and y, and z. And so on.
Obviously the body shall not collide with itself, but this could be easily fixed by either modifying the collide function or by filtering the input list to List.fold and removing the currently being computed element. This is left as an exercise.
List.map returns a new list. The function you supply to List.map may transform the elements from one type to another or just apply some operation on the same type.
For example, let's assume you start with a list of integer tuples
let int_tuples = [(1, 3); (4, 3); (8, 2)];;
and let's assume that your update function takes an integer tuple and doubles the integers:
let update (i, j) = (i * 2, j * 2) (* update maybe your collide function *)
If you now do:
let new_int_tuples = List.map update int_tuples
You'll get
(* [(2, 6); (8, 6); (16, 4)] *)
Hope this helps

Type issues with anonymous functions in Purescript

I am working through the Purescript By Example tutorial and I am having trouble getting types to line up using a fold left as such:
smallestFile' :: [Path] -> Maybe Path
smallestFile' (x : xs) = foldl(\acc i -> smallerFile(acc i) ) Just(x) xs // Error is on this line
smallerFile :: Maybe Path -> Path -> Maybe Path
smallerFile maybeA b = do
a <- maybeA
sa <- size a
sb <- size b
if sa > sb then return(b) else return(a)
The error I am receiving is on the fold left and is
Cannot unify Prim.Function u13116 with Data.Maybe.Maybe
I believe that the types line up, but I cannot make heads or tails of this error.
Also, is it possible to clean up the anonymous function syntax so that
foldl(\acc i -> smallerFile(acc i) ) Just(x) xs
becomes something like:
foldl smallerFile Just(x) xs
In PureScript, like Haskell, function application uses whitespace, and associates to the left, which means that f x y z parses as ((f x) y) z. You only need parentheses when terms need to be regrouped. It looks like you're trying to use parentheses for function application.
I suspect what you want to write is
foldl (\acc i -> smallerFile acc i) (Just x) xs
The argument to foldl is a function which takes two arguments acc and i and returns the application smallerFile acc i. This is equivalent to the double application (smallerFile acc) i. First we apply the argument acc, then the second argument i. The precedence rule for function application in the parser makes these equivalent.
Also, Just x needs to be parenthesized because what you wrote parses as
foldl (\acc i -> smallerFile (acc i)) Just x xs
which provides too many arguments to foldl.
Once you have the correct version, you can notice that \acc i -> smallerFile acc i is equivalent to \acc -> (\i -> (smallerFile acc) i). The inner function applies its argument i immediately, so we can simplify this to \acc -> smallerFile acc. Applying this simplification a second time, we get just smallerFile, so the code becomes:
foldl smallerFile (Just x) xs
so the only mistake in the end was the incorrect bracketing of Just x.

Recursive anonymous functions in SML

Is it possible to write recursive anonymous functions in SML? I know I could just use the fun syntax, but I'm curious.
I have written, as an example of what I want:
val fact =
fn n => case n of
0 => 1
| x => x * fact (n - 1)
The anonymous function aren't really anonymous anymore when you bind it to a
variable. And since val rec is just the derived form of fun with no
difference other than appearance, you could just as well have written it using
the fun syntax. Also you can do pattern matching in fn expressions as well
as in case, as cases are derived from fn.
So in all its simpleness you could have written your function as
val rec fact = fn 0 => 1
| x => x * fact (x - 1)
but this is the exact same as the below more readable (in my oppinion)
fun fact 0 = 1
| fact x = x * fact (x - 1)
As far as I think, there is only one reason to use write your code using the
long val rec, and that is because you can easier annotate your code with
comments and forced types. For examples if you have seen Haskell code before and
like the way they type annotate their functions, you could write it something
like this
val rec fact : int -> int =
fn 0 => 1
| x => x * fact (x - 1)
As templatetypedef mentioned, it is possible to do it using a fixed-point
combinator. Such a combinator might look like
fun Y f =
let
exception BlackHole
val r = ref (fn _ => raise BlackHole)
fun a x = !r x
fun ta f = (r := f ; f)
in
ta (f a)
end
And you could then calculate fact 5 with the below code, which uses anonymous
functions to express the faculty function and then binds the result of the
computation to res.
val res =
Y (fn fact =>
fn 0 => 1
| n => n * fact (n - 1)
)
5
The fixed-point code and example computation are courtesy of Morten Brøns-Pedersen.
Updated response to George Kangas' answer:
In languages I know, a recursive function will always get bound to a
name. The convenient and conventional way is provided by keywords like
"define", or "let", or "letrec",...
Trivially true by definition. If the function (recursive or not) wasn't bound to a name it would be anonymous.
The unconventional, more anonymous looking, way is by lambda binding.
I don't see what unconventional there is about anonymous functions, they are used all the time in SML, infact in any functional language. Its even starting to show up in more and more imperative languages as well.
Jesper Reenberg's answer shows lambda binding; the "anonymous"
function gets bound to the names "f" and "fact" by lambdas (called
"fn" in SML).
The anonymous function is in fact anonymous (not "anonymous" -- no quotes), and yes of course it will get bound in the scope of what ever function it is passed onto as an argument. In any other cases the language would be totally useless. The exact same thing happens when calling map (fn x => x) [.....], in this case the anonymous identity function, is still in fact anonymous.
The "normal" definition of an anonymous function (at least according to wikipedia), saying that it must not be bound to an identifier, is a bit weak and ought to include the implicit statement "in the current environment".
This is in fact true for my example, as seen by running it in mlton with the -show-basis argument on an file containing only fun Y ... and the val res ..
val Y: (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b
val res: int32
From this it is seen that none of the anonymous functions are bound in the environment.
A shorter "lambdanonymous" alternative, which requires OCaml launched
by "ocaml -rectypes":
(fun f n -> f f n)
(fun f n -> if n = 0 then 1 else n * (f f (n - 1))
7;; Which produces 7! = 5040.
It seems that you have completely misunderstood the idea of the original question:
Is it possible to write recursive anonymous functions in SML?
And the simple answer is yes. The complex answer is (among others?) an example of this done using a fix point combinator, not a "lambdanonymous" (what ever that is supposed to mean) example done in another language using features not even remotely possible in SML.
All you have to do is put rec after val, as in
val rec fact =
fn n => case n of
0 => 1
| x => x * fact (n - 1)
Wikipedia describes this near the top of the first section.
let fun fact 0 = 1
| fact x = x * fact (x - 1)
in
fact
end
This is a recursive anonymous function. The name 'fact' is only used internally.
Some languages (such as Coq) use 'fix' as the primitive for recursive functions, while some languages (such as SML) use recursive-let as the primitive. These two primitives can encode each other:
fix f => e
:= let rec f = e in f end
let rec f = e ... in ... end
:= let f = fix f => e ... in ... end
In languages I know, a recursive function will always get bound to a name. The convenient and conventional way is provided by keywords like "define", or "let", or "letrec",...
The unconventional, more anonymous looking, way is by lambda binding. Jesper Reenberg's answer shows lambda binding; the "anonymous" function gets bound to the names "f" and "fact" by lambdas (called "fn" in SML).
A shorter "lambdanonymous" alternative, which requires OCaml launched by "ocaml -rectypes":
(fun f n -> f f n)
(fun f n -> if n = 0 then 1 else n * (f f (n - 1))
7;;
Which produces 7! = 5040.

Multiple set comprehension in a functional style

Does any one know of a function/idiom (in any language) that takes a set and returns two or more subsets, determined by one or more predicates?
It is easy to do this in an imperative style e.g:
a = b = []
for x in range(10):
if even(x):
a.append(x)
else:
b.append(x)
or slightly better:
[even(x) and a.append(x) or b.append(x) for x in range(10)]
Since a set comprehension returns a single list based upon a single predicate (and it effectively just a map) I think there ought to be something that splits the input into 2 or more bins based on either a binary predicate or multiple predicates.
The neatest syntax I can come up with is:
>> def partition(iterable, *functions):
>> return [filter(f,iterable) for f in functions]
>> partition(range(10), lambda x: bool(x%2), lambda x: x == 2)
[[1, 3, 5, 7, 9], [2]]
Searching for (a -> Bool) -> [a] -> ([a], [a]) on Hoogle yields Data.List.partition.
The partition function takes a predicate a list and returns the pair of lists of elements which do and do not satisfy the predicate, respectively; i.e.,
partition p xs == (filter p xs, filter (not . p) xs)
If you look at its source and translate to Python,
def partition(predicate, sequence):
def select((yes, no), value):
if predicate(value):
return (yes + [value], no)
else:
return (yes, no + [value])
return reduce(select, sequence, ([], []))
which is pretty nicely functional. Unlike the original, it's not lazy, but that's a bit trickier to pull off in Python.
Ruby's Enumerable mixin has a partition method that does what you describe.

Ocaml continuation passing style

I'm new to ocaml and tryin to write a continuation passing style function but quite confused what value i need to pass into additional argument on k
for example, I can write a recursive function that returns true if all elements of the list is even, otherwise false.
so its like
let rec even list = ....
on CPS, i know i need to add one argument to pass function
so like
let rec evenk list k = ....
but I have no clue how to deal with this k and how does this exactly work
for example for this even function, environment looks like
val evenk : int list -> (bool -> ’a) -> ’a = <fun>
evenk [4; 2; 12; 5; 6] (fun x -> x) (* output should give false *)
The continuation k is a function that takes the result from evenk and performs "the rest of the computation" and produces the "answer". What type the answer has and what you mean by "the rest of the computation" depends on what you are using CPS for. CPS is generally not an end in itself but is done with some purpose in mind. For example, in CPS form it is very easy to implement control operators or to optimize tail calls. Without knowing what you are trying to accomplish, it's hard to answer your question.
For what it is worth, if you are simply trying to convert from direct style to continuation-passing style, and all you care about is the value of the answer, passing the identity function as the continuation is about right.
A good next step would be to implement evenk using CPS. I'll do a simpler example.
If I have the direct-style function
let muladd x i n = x + i * n
and if I assume CPS primitives mulk and addk, I can write
let muladdk x i n k =
let k' product = addk x product k in
mulk i n k'
And you'll see that the mulptiplication is done first, then it "continues" with k', which does the add, and finally that continues with k, which returns to the caller. The key idea is that within the body of muladdk I allocated a fresh continuation k' which stands for an intermediate point in the multiply-add function. To make your evenk work you will have to allocate at least one such continuation.
I hope this helps.
Whenever I've played with CPS, the thing passed to the continuation is just the thing you would normally return to the caller. In this simple case, a nice "intuition lubricant" is to name the continuation "return".
let rec even list return =
if List.length list = 0
then return true
else if List.hd list mod 2 = 1
then return false
else even (List.tl list) return;;
let id = fun x -> x;;
Example usage: "even [2; 4; 6; 8] id;;".
Since you have the invocation of evenk correct (with the identity function - effectively converting the continuation-passing-style back to normal style), I assume that the difficulty is in defining evenk.
k is the continuation function representing the rest of the computation and producing a final value, as Norman said. So, what you need to do is compute the result of v of even and pass that result to k, returning k v rather than just v.
You want to give as input the result of your function as if it were not written with continuation passing style.
Here is your function which tests whether a list has only even integers:
(* val even_list : int list -> bool *)
let even_list input = List.for_all (fun x -> x mod 2=0) input
Now let's write it with a continuation cont:
(* val evenk : int list -> (bool -> 'a) -> 'a *)
let evenk input cont =
let result = even_list input in
(cont result)
You compute the result your function, and pass resultto the continuation ...

Resources