If I want a function that subtracts an int argument from the number 2, I can do
let two_minus = (-) 2
But what if I want a function that subtracts 2 from an int argument?
In Haskell, I can do
let minus2 = flip (-) 2
But in Ocaml 4.02, flip is not part of the standard library.
For now, I've settled on
let minus2 = (+) ~-2
which adds negative 2 to an int argument. I find it looks cleaner than
let minus2 = fun x -> x-2
... or at least it takes less characters.
Is there a better, more idiomatic way?
In Haskell, you can do what you want with operator sections, which is much cleaner than flip imo:
Prelude> :t (2 -)
(2 -) :: Num a => a -> a
Prelude> :t ((-) 2)
((-) 2) :: Num a => a -> a
OCaml does not support this nicety (afaik). However, if you like flip, it is trivial to define your own:
let flip f x y = f y x;;
Or you can use a standard library that has it defined already, like Core and Batteries. E.g.,
# open Core
utop # Fn.flip;;
- : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c = <fun>
fwiw, in the absence of operator sections, I find fun x -> x-2 much clearer than either of the two alternatives you propose. It may not look as nice, but it is immediately clear what it means.
Favoring clear and very explicit expressions over clever and concise ones is very idiomatic OCaml.
OCaml is a programming language. You are free to define whatever you feel convenient:
let flip f x y = f y x
Related
List.map is of type
- : ('a -> 'b) -> 'a list -> 'b list = <fun>
It's easy for me to understand the following code:
List.map (fun x -> x+1) [1;2;3;4];;
which adds 1 to each element of the list so it returns the following list :
- : int list = [2;3;4;5]
Now this is in an exercise where I'm asked to indicate the type of this :
List.map (fun p -> p 7) [ (fun n m -> n + m) ];;
I don't understand at all what it means to be honest.
What does p 7 mean ?
Why is there a function in the list ?
The type is
- : (int -> int) list = [<fun>]
But I can't understand why.
What does it mean when fun is between brackets ?
Thank you.
What does p 7 mean?
It means the application of function p to argument 7 .... You might spend some time reading the wikipage on λ-calculus (at least to learn about functional abstraction)
Read also about currying.
Why is there a function in the list ?
In Ocaml, functions are values, so you can have list of functions. If it was not a list of functions, you'll get a typing error. If you think more, you can understand what kind of functions are allowed.
What does it mean when fun is between brackets ?
The toplevel is not able to print functional values (implemented as closures). It shows them as <fun>. For a simpler example, pass fun x -> x+1;; (then try also fun y -> y;;) to your REPL.
(the rest of the exercise is left to the reader)
Is it ok to use Lwt.return as the final call in a recursive function?
I have a function that compiles fine but does not run properly and it looks like the function f below. Please assume that there is no issue with any function provided as g in this example, I am basically just trying to find out if it is ok to have a function with the following form or if there is a better/simpler (and Lwt compliant) way of doing the following:
let rec f (x : string list) (g : string -> unit Lwt.t) =
match List.length x with
| 0 -> Lwt.return ()
| _ -> g (List.hd x) >>= fun () -> f (List.tl x) g
;;
val f : string list -> (string -> unit Lwt.t) -> unit Lwt.t = <fun>
I am pretty sure that I am doing it wrong. But the actual function I am using is much more complex than this example so I am having a difficult time debugging it.
First of all the correct way of dealing with lists in OCaml is deconstructing them with pattern matching, like this:
let rec f (xs : string list) (g : string -> unit Lwt.t) =
match xs with
| [] -> return ()
| x :: xs -> g x >>= fun () -> f xs g
The next step would be notice, that you're actually just perform iteration over a list. There is a Lwt_list.iter_s for this:
let f g xs = Lwt_list.iter_s g xs
That can simplified even more
let f = Lwt_list.iter_s
That means, that you even do not need to write such function, since it is already there.
And finally, there was no issues with recursion in your original implementation. The function that you've provided was tail recursive.
It depends whether g returns an lwt thread that is already computed such as return () or scheduled and woken up later by the lwt scheduler. In the former case, it's possible that the call to fun () -> f (List.tl x) g is made right away instead of being scheduled for later, and that could grow the stack depending on what optimizations are happening.
I don't think your code should rely on such tricky behavior. For this particular example, as suggested in #ivg's answer, you should use the functions from the Lwt_list module.
It's a good idea to look at the implementation of the Lwt_list module to see how it's done. The same advice goes for the OCaml standard library as well.
In OCaml, is there a way to refer to the cons operator by itself?
For example, I can use (+) and ( * ) as int -> int -> int functions, but I cannot use (::) as a 'a -> 'a list -> 'a list function, as the following example show:
# (+) 3 5;;
- : int = 8
# ( * ) 4 6;;
- : int = 24
# (::) 1 [2;3;4];;
Error: Syntax error: operator expected.
Is there a way to produce a result like (::) other than with fun x y -> x::y? And does anyone know why (::) wasn't implemented in OCaml?
Adding to the answer of #seanmcl,
Actually OCaml supports a prefix form of (::):
# (::)(1, []);;
- : int list = [1]
This is in the uncurried form, corresponding with the fact that all the OCaml variant constructors are not curried and cannot be partially applied. This is handled by a special parsing rule just for (::), which is why you got a rather strange error message Error: Syntax error: operator expected..
Update:
Upcoming OCaml 4.02 removes this parsing rule, therefore this is no longer available.
No. Cons (::) is a constructor, constructors can not be infix operators. The allowed infix symbols are here:
http://caml.inria.fr/pub/docs/manual-caml-light/node4.9.html
Some workarounds are (as you mention) the verbose
(fun x l -> x :: l)
and defining your own nontraditional infix cons
let (+:) x l = x :: l
As of Ocaml 4.03, you can now use cons (in the List module). That is, cons x xs is the same as x :: xs.
It's also possible to just define your own cons function:
let cons = fun a list -> a :: list
So I'm writing a combining function for fold that will make it perform filtering.
let filter_combine (pred: 'a -> bool) : a' list -> 'a list -> 'a list =
fun (x: 'a) (y: 'a list) -> x :: (filter pred y)
I am not having any compilation issues, but one out of my two test cases is failing. What is wrong with my implementation?
This is the test case that fails...
[-1; 1] = fold (filter_combine (fun (x: int) -> (abs x) mod 2 <> 0)) [] [-2; -1; 0; 1; 2]
This is the one that works...
[-2; 2] = fold (filter_combine (fun (x: int) -> (abs x) > 1)) [] [-2; -1; 0; 1; 2]
I'm having some trouble understanding this question. I think what you're saying is that you want to write a function that takes a predicate and returns a function suitable for use with a fold so that the result will filter according to the predicate.
Some problems with the question:
There's no built-in OCaml function named fold.
If you're supposed to implement filtering, it seems fairly weird to use filter in your implementation.
If I assume you're using fold_right, then it seems to me you'd want to return a function of type a -> a list -> a list. It wants to look at one thing to decide what to do, not at a whole list of things. Since you say you're not getting compilation errors, this suggests that your function named fold doesn't work as I would expect. It might help if you showed how fold actually works.
I need to find a way to combine two functions and output them as one.
I have the following code where take in a list of function ('a->'a) list then output a function ('a->'a) using the List.fold_left.
I figured out the base case, but I tried a lot of ways to combine two functions. The output should have the type ('a -> 'a) list -> ('a -> 'a).
example output:
# pipe [] 3;;
- : int = 3
# pipe [(fun x-> 2*x);(fun x -> x + 3)] 3 ;;
- : int = 9
# pipe [(fun x -> x + 3);(fun x-> 2*x)] 3;;
- : int = 12
function:
let p l =
let f acc x = fun y-> fun x->acc in (* acc & x are functions 'a->'a *)
let base = fun x->x in
List.fold_left f base l
Since you know that you have to use a left fold, you now have to solve a fairly constrained problem: given two functions of type 'a -> 'a, how do you combine them into a single function of the same type?
In practice, there is one general way of combining functions: composition. In math, this is usually written as f ∘ g where f and g are the functions. This operation produces a new function which corresponds to taking an argument, applying g to it and then applying f to the result. So if h = f ∘ g, then we can also write this as h(x) = f(g(x)).
So your function f is actually function composition. (You should really give it a better name than f.) It has to take in two functions of type 'a -> 'a and produce another function of the same type. This means it produces a function of one argument where you produce a function taking two arguments.
So you need to write a function compose (a more readable name than f) of type ('a -> 'a) -> ('a -> 'a) -> ('a -> 'a). It has to take two arguments f and g and produce a function that applies both of them to its argument.
I hope this clarifies what you need to do. Figuring out exactly how to do it in OCaml is a healthy exercise.