Order of Evaluation of Arguments in Ocaml - function

I would like to know why does ocaml evaluate the calls from right to left, is that a FP principle or it doesn't matter at all to a FP language ?
A quicksort example :
let rec qs = function
| [] -> []
| h::t -> let l, r = List.partition ((>) h) t in
List.iter (fun e -> print_int e; print_char ' ') l; Printf.printf " <<%d>> " h;
List.iter (fun e -> print_int e; print_char ' ') r; print_char '\n';
(qs l)#(h::qs r)
In my example the call to (qs r) is evaluated first and then (qs l) but I expected it to be otherwise.
# qs [5;43;1;10;2];;
1 2 <<5>> 43 10
10 <<43>>
<<10>>
<<1>> 2
<<2>>
- : int list = [1; 2; 5; 10; 43]
EDIT :
from https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora029.html
In Objective CAML, the order of evaluation of arguments is not
specified. As it happens, today all implementations of Objective CAML
evaluate arguments from left to right. All the same, making use of
this implementation feature could turn out to be dangerous if future
versions of the language modify the implementation.

The order of evaluation of arguments to a function is not specified in OCaml.
This is documented in Section 6.7 of the manual.
In essence this gives the greatest possible freedom to the system (compiler or interpreter) to evaluate expressions in an order that is advantageous in some way. It means you (as an OCaml programmer) must write code that doesn't depend on the order of evaluation.
If your code is purely functional, its behavior can't depend on the order. So you need to be careful only when writing code with effects.
Update
If you care about order, use let:
let a = <expr1> in
let b = <expr2> in
f a b
Or, more generally:
let f = <expr0> in
let a = <expr1> in
let b = <expr2> in
f a b
Update 2
For what it's worth, the book you cite above was published in 2002. A lot has changed since then, including the name of the language. A more current resource is Real World OCaml.

Related

What's wrong with this recursive curried function

I was trying to write a function that solves following;
persistence 39 = 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence 999 = 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence 4 = 0 // because 4 is already a one-digit number
After I solved the question I tried to make all functions looks like Ramda.js function styles like this;
This code works;
let multiply = List.reduce (*)
let gt from input = input > from
let just input = fun _ -> input
let ifElse cond trueFn falseFn input =
if cond input then trueFn input else falseFn input
let digits n =
(string n) |> Seq.toList |> List.map (System.Char.GetNumericValue >> int)
let rec persRec iter current =
current
|> digits
|> multiply
|> ifElse (gt 9) (persRec (iter + 1)) (just iter)
let persistence n = if n > 9 then persRec 1 n else 0
But when I tried to modify persRec function with a curried composed version like following, it makes this stack overflow.
let rec persRec iter =
digits
>> multiply
>> ifElse (gt 9) (persRec (iter + 1)) (just iter)
What's wrong with this?
The function persRec is calling itself unconditionally. Here:
>> ifElse (gt 9) (persRec (iter + 1)) (just iter)
^^^^^^^^^^^^^^^^^^^^
|
unconditional recursive call
This happens always. Every time persRec is called by somebody, it immediately calls itself right away.
You may expect that the recursive call should only happen when gt 9, because, after all, it's inside an ifElse, right? But that doesn't matter: ifElse is not special, it's just a function. In order to call a function, F# has to compute all its parameter before the call (aka "applicative order of evaluation"), which means it has to call persRec (iter + 1) before it can call ifElse, and it has to call ifElse before it can call (>>), and it has to call (>>) in order to compute result of persRec. So ultimately, it needs to call persRec in order to compute the result of persRec. See where this is going?
The previous version works, because the body of persRec is not actually executed before the call to ifElse. The body of persRec will only be executed when all its parameters are supplied, and the last parameter will only be supplied inside the body of ifElse when the condition is true.
The way I see it, the confusion stems from the difference between denotational and operational semantics. Yes, mathematically, logically, the functions are equivalent. But execution also matters. Normal vs. applicative evaluation order. Memory concerns. Performance. Those are all outside of the domain of lambda-calculus.

Feeding data to Haskell twice function as explained by Erik Meijer lecture 7

Can somebody point me to how to feed data to:
twice f x = f (f x)
It's taken from Erik Meijer's lecture, and I have the feeling I can only truely understand when passing data to it. Now this only results in errors.
The derived type signature is (t -> t) -> t -> t. Pass any arguments that match and you won't get compiler errors. One example is twice (+1) 0.
The main mistake here is disregarding the type of twice. In Haskell types are very important, and explain precisely how you would call such a function.
twice :: (a -> a) -> a -> a
So, the function works in this way:
the caller chooses any type a they want
the caller passes a function f of type a -> a
the caller passes an argument of type a
twice finally produces a value of type a
Hence, we could do the following. We can choose, for instance, a = Int. Then define the function f as
myFun :: Int -> Int
myFun y = y*y + 42
then choose x :: Int as 10. Finally, we can make the call
twice myFun 10
Alternatively, we can use a lambda and skip the function definition above
twice (\y -> y*y + 42) 10
For illustration here are three functions called erik1, erik2, and erik3 with the same type signature.
erik1, erik2, erik3 ::(a -> a) -> a -> a
erik1 f x = f x
erik2 f x = f(f x) -- Equivalent to "twice"
erik3 f x = f(f(f x))
These eriks take two arguments, the first being a function and the second being a number. Let's choose sqrt as the function and the number to be 16 and run the three eriks. Here's what you get:
*Main> erik1 sqrt 16
4.0
*Main> erik2 sqrt 16
2.0
*Main> erik3 sqrt 16
1.4142135623730951
There are many things you can try, such as erik3 (/2) 16 = 2,because the f in the function allows you to use any appropriate function. In the particular case of sqrt, erik3 is equivalent to this statement in C:
printf ("Eighth root of 16 = %f \n", sqrt(sqrt(sqrt(16))));
Dr. Meijer Ch 7 1:48 to 3:37
As I watched this lecture last night a key point was made when Erik wrote the type signature as twice :: (a -> a) -> (a -> a) and said, "twice is a function that takes a to a and returns a new function from a to a, and by putting some extra parens it becomes painfully obvious that twice is a higher order function."
A C example that comes closer to illustrating that is:
#define eighthRoot(x) (sqrt(sqrt(sqrt(x))))
printf ("eigthtRoot(16) = %f \n", eighthRoot(16));

Weeding duplicates from a list of functions

Is it possible to remove the duplicates (as in nub) from a list of functions in Haskell?
Basically, is it possible to add an instance for (Eq (Integer -> Integer))
In ghci:
let fs = [(+2), (*2), (^2)]
let cs = concat $ map subsequences $ permutations fs
nub cs
<interactive>:31:1:
No instance for (Eq (Integer -> Integer))
arising from a use of `nub'
Possible fix:
add an instance declaration for (Eq (Integer -> Integer))
In the expression: nub cs
In an equation for `it': it = nub cs
Thanks in advance.
...
Further, based on larsmans' answer, I am now able to do this
> let fs = [AddTwo, Double, Square]
> let css = nub $ concat $ map subsequences $ permutations fs
in order to get this
> css
[[],[AddTwo],[Double],[AddTwo,Double],[Square],[AddTwo,Square],[Double,Square],[AddTwo,Double,Square],[Double,AddTwo],[Double,AddTwo,Square],[Square,Double],[Square,AddTwo],[Square,Double,AddTwo],[Double,Square,AddTwo],[Square,AddTwo,Double],[AddTwo,Square,Double]]
and then this
> map (\cs-> call <$> cs <*> [3,4]) css
[[],[5,6],[6,8],[5,6,6,8],[9,16],[5,6,9,16],[6,8,9,16],[5,6,6,8,9,16],[6,8,5,6],[6,8,5,6,9,16],[9,16,6,8],[9,16,5,6],[9,16,6,8,5,6],[6,8,9,16,5,6],[9,16,5,6,6,8],[5,6,9,16,6,8]]
, which was my original intent.
No, this is not possible. Functions cannot be compared for equality.
The reason for this is:
Pointer comparison makes very little sense for Haskell functions, since then the equality of id and \x -> id x would change based on whether the latter form is optimized into id.
Extensional comparison of functions is impossible, since it would require a positive solution to the halting problem (both functions having the same halting behavior is a necessary requirement for equality).
The workaround is to represent functions as data:
data Function = AddTwo | Double | Square deriving Eq
call AddTwo = (+2)
call Double = (*2)
call Square = (^2)
No, it's not possible to do this for Integer -> Integer functions.
However, it is possible if you're also ok with a more general type signature Num a => a -> a, as your example indicates! One naïve way (not safe), would go like
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
data NumResLog a = NRL { runNumRes :: a, runNumResLog :: String }
deriving (Eq, Show)
instance (Num a) => Num (NumResLog a) where
fromInteger n = NRL (fromInteger n) (show n)
NRL a alog + NRL b blog
= NRL (a+b) ( "("++alog++ ")+(" ++blog++")" )
NRL a alog * NRL b blog
= NRL (a*b) ( "("++alog++ ")*(" ++blog++")" )
...
instance (Num a) => Eq (NumResLog a -> NumResLog a) where
f == g = runNumResLog (f arg) == runNumResLog (g arg)
where arg = NRL 0 "THE ARGUMENT"
unlogNumFn :: (NumResLog a -> NumResLog c) -> (a->c)
unlogNumFn f = runNumRes . f . (`NRL`"")
which works basically by comparing a "normalised" version of the functions' source code. Of course this fails when you compare e.g. (+1) == (1+), which are equivalent numerically but yield "(THE ARGUMENT)+(1)" vs. "(1)+(THE ARGUMENT)" and thus are indicated as non-equal. However, since functions Num a => a->a are essentially constricted to be polynomials (yeah, abs and signum make it a bit more difficult, but it's still doable), you can find a data type that properly handles those equivalencies.
The stuff can be used like this:
> let fs = [(+2), (*2), (^2)]
> let cs = concat $ map subsequences $ permutations fs
> let ncs = map (map unlogNumFn) $ nub cs
> map (map ($ 1)) ncs
[[],[3],[2],[3,2],[1],[3,1],[2,1],[3,2,1],[2,3],[2,3,1],[1,2],[1,3],[1,2,3],[2,1,3],[1,3,2],[3,1,2]]

How to pass the return type of a function to an exception in OCaml?

I have function 'my_a' in OCaml, which could have a very complicated return type:
exception Backtrack
exception Continue of (* How do I put the type of function 'my_a' here? *)
let my_a arg = try do_stuff (List.hd arg)
with
| Backtrack -> my_a (List.tl arg)
| Continue (found_answer) -> (try my_a (List.tl arg)
with
| Backtrack -> raise Continue(found_answer)
| Continue (other_answer) ->
raise Continue (compare_answer(found_answer,other_answer));;
(* the caller of my_a will handle the Continue exception to catch the found value
if something was found*)
This is my problem: I'm using backtrack to find a solution. When a backtrack exception is raised by do_stuff, there was no solution going that path. However, when it raises an exception of type Continue, it means it found a solution, but, it may not be the best solution there is, that's when I try again with a different path. If there is another exception, I want to return the answer it already had found.
The thing is, to be able to use that feature of OCaml I need to to tell it what data type Continue will be carrying. What the OCaml top level returns when i define my_a:
'a * ('a -> ('a, 'b) symbol list list) ->
'b list -> ('a * ('a, 'b) symbol list) list * 'b list = <fun>
Does anyone have any idea of how to do that, or a different solution to that?
It's hard to tell exactly what you're asking. I think you might be asking how to get the type inside the Two exception to be set to the return type of A without having to specifically declare this type. I can't think of any way to do it.
Things might go better if you used option types instead of exceptions. Or you can just declare the return type of A explicitly. It might be good documentation.
A couple of side comments: (a) function names have to start with a lower case letter (b) this code looks quite convoluted and hard to follow. There might be a simpler way to structure your computation.
You are gaining nothing by using exceptions. Here is a possible solution.
(** There are many ways to implement backtracking in Ocaml. We show here one
possibility. We search for an optimal solution in a search space. The
search space is given by an [initial] state and a function [search] which
takes a state and returns either
- a solution [x] together with a number [a] describing how good [x] is
(larger [a] means better solution), or
- a list of states that need still to be searched.
An example of such a problem: given a number [n], express it as a sum
[n1 + n2 + ... + nk = n] such that the product [n1 * n2 * ... * nk] is
as large as possible. Additionally require that [n1 <= n2 <= ... <= nk].
The state of the search can be expressed as pair [(lst, s, m)] where
[lst] is the list of numbers in the sum, [s] is the sum of numbers in [lst],
and [m] is the next number we will try to add to the list. If [s = n] then
[lst] is a solution. Otherwise, if [s + m <= n] then we branch into two states:
- either we add [m] to the list, so the next state is [(m :: lst, m+s, m)], or
- we do not add [m] to the list, and the next state is [(lst, s, m+1)].
The return type of [search] is described by the following datatype:
*)
type ('a, 'b, 'c) backtrack =
| Solution of ('a * 'b)
| Branches of 'c list
(** The main function accepts an initial state and the search function. *)
let backtrack initial search =
(* Auxiliary function to compare two optional solutions, and return the better one. *)
let cmp x y =
match x, y with
| None, None -> None (* no solution *)
| None, Some _ -> y (* any solution is better than none *)
| Some _, None -> x (* any solution is better than none *)
| Some (_, a), Some (_, b) ->
if a < b then y else x
in
(* Auxiliary function which actually performs the search, note that it is tail-recursive.
The argument [best] is the best (optional) solution found so far, [branches] is the
list of branch points that still needs to be processed. *)
let rec backtrack best branches =
match branches with
| [] -> best (* no more branches, return the best solution found *)
| b :: bs ->
(match search b with
| Solution x ->
let best = cmp best (Some x) in
backtrack best bs
| Branches lst ->
backtrack best (lst # bs))
in
(* initiate the search with no solution in the initial state *)
match backtrack None [initial] with
| None -> None (* nothing was found *)
| Some (x, _) -> Some x (* the best solution found *)
(** Here is the above example encoded. *)
let sum n =
let search (lst, s, m) =
if s = n then
(* solution found, compute the product of [lst] *)
let p = List.fold_left ( * ) 1 lst in
Solution (lst, p)
else
if s + m <= n then
(* split into two states, one that adds [m] to the list and another
that increases [m] *)
Branches [(m::lst, m+s, m); (lst, s, m+1)]
else
(* [m] is too big, no way to proceed, return empty list of branches *)
Branches []
in
backtrack ([], 0, 1) search
;;
(** How to write 10 as a sum of numbers so that their product is as large as possible? *)
sum 10 ;; (* returns Some [3; 3; 2; 2] *)
OCaml happily informs us that the type of backtrack is
'a -> ('a -> ('b, 'c, 'a) backtrack) -> 'b option
This makes sense:
the first argument is the initial state, which has some type 'a
the second argument is the search function, which takes a state of type 'a and
returns either a Solution (x,a) where x has type 'b and a has type 'c,
or Branches lst where lst has type 'a list.

OCaml: Using a comparison operator passed into a function

I'm an OCaml noob. I'm trying to figure out how to handle a comparison operator that's passed into a function.
My function just tries to pass in a comparison operator (=, <, >, etc.) and an int.
let myFunction comparison x =
if (x (comparison) 10) then
10
else
x;;
I was hoping that this code would evaluate to (if a "=" were passed in):
if (x = 10) then
10
else
x;;
However, this is not working. In particular, it thinks that x is a bool, as evidenced by this error message:
This expression has type 'a -> int -> bool
but an expression was expected of type int
How can I do what I'm trying to do?
On a side question, how could I have figured this out on my own so I don't have to rely on outside help from a forum? What good resources are available?
Comparison operators like < and = are secretly two-parameter (binary) functions. To pass them as a parameter, you use the (<) notation. To use that parameter inside your function, you just treat it as function name:
let myFunction comp x =
if comp x 10 then
10
else
x;;
printf "%d" (myFunction (<) 5);; (* prints 10 *)
OCaml allows you to treat infix operators as identifiers by enclosing them in parentheses. This works not only for existing operators but for new ones that you want to define. They can appear as function names or even as parameters. They have to consist of symbol characters, and are given the precedence associated with their first character. So if you really wanted to, you could use infix notation for the comparison parameter of myFunction:
Objective Caml version 3.12.0
# let myFunction (#) x =
x # 10;;
val myFunction : ('a -> int -> 'b) -> 'a -> 'b = <fun>
# myFunction (<) 5;;
- : bool = true
# myFunction (<) 11;;
- : bool = false
# myFunction (=) 10;;
- : bool = true
# myFunction (+) 14;;
- : int = 24
#
(It's not clear this makes myFunction any easier to read. I think definition of new infix operators should be done sparingly.)
To answer your side question, lots of OCaml resources are listed on this other StackOverflow page:
https://stackoverflow.com/questions/2073436/ocaml-resources
Several possibilities:
Use a new definition to redefine your comparison operator:
let myFunction comparison x =
let (#) x y = comparison x y in
if (x # 10) then
10
else
x;;
You could also pass the # directly without the extra definition.
As another solution you can use some helper functions to define what you need:
let (/*) x f = f x
let (*/) f x = f x
let myFunction comparison x =
if x /* comparison */ 10 then
10
else
x