Just a quick question. I'm wondering if there is a infix function composition operator in OCaml defined in the standard library (or in Jane Street's Core or in Batteries) like the (.) function in Haskell which saves us a lot parentheses since we can write (f . g . h) x instead of the less appealing f (g (h x))).
Thanks folks.
The answer here is the same as for flip :-). Function composition isn't defined in the OCaml standard library. In this case, it isn't something I miss once in a while, I miss it all the time.
The OCaml Batteries Included project defines function composition (in the order you give) using the operator -| in the BatStd module. As lukstafi points out (see below), this operator will apparently change to % in a future release of Batteries. (I've verified this in their source tree.)
As far as I can see, the Jane Street Core project doesn't define a function composition operator. It defines a function compose in the Fn module.
I just want to add that the operator is fairly easy to include, in F# it's simply defined as:
let (<<) f g x = f(g(x));;
which has the type signature: val ( << ) : f:('a -> 'b) -> g:('c -> 'a) -> x:'c -> 'b doing exactly what you need...
(f << g << h) x = f(g(h(x))
so you don't need the batteries project if you don't have to
I'd like to add that the reason it looks like << is, as you might guess, because the >> operator does the opposite:
let (>>) f g x = g(f(x));;
(f >> g >> h) x = h(g(f(x))
There is Fn.compose function in Core, but it is not an infix operator. Also, it is implemented as a regular function and has runtime overhead.
In practice, it is pretty convenient to use pipe operator. It has no runtime overhead as implemented directly in compiler (starting from 4.00). See Optimized Pipe Operators for more details.
Pipe operator is available as '|>' in Core. So, you can rewrite your expression as following: h x |> g |> f
The use of an infix composition operator seems to be discouraged. (see this discussion).
You can write f ## g ## h x instead of f (g (h x))).
In Containers (yet another stdlib replacement for Ocaml), the function composition operator is called % and can be found in the CCFun module:
open Containers
open Fun
let is_zero n = (n = 0)
let nonzeros = List.filter (not % is_zero) [0;1;2;3;0]
Maybe that could help you.
let identite f = f
let (>>) = List.fold_right identite
test:
# let f=fun x-> x+1 and
g=fun x-> x*2 and
h=fun x-> x+3;;
# [f;g;h] >> 2;;
- : int = 11
Related
I'm quite new to the Ocaml language and in general a newbie in programming. So I feel like this question is very basic but here it is:
I would like to recreate the List.iter function in Ocaml to understand it better and because I've been asked to by my teacher.
Here's what I've done :
let rec iter f = function
|[]->()
|e::q-> f e (iter f q);;
My two very simple problems are
I don't really understand how List.iter works
this results in ('a -> unit -> unit) -> 'a list -> unit = and I know my 'f' should only be a
'a->unit and I don't know how to change it
(If I made any mistakes, I'm sorry, my native language is french)
The definition of List.iter is something like this. This function call:
List.iter f [x1; x2; ...; xn]
is equivalent to these separate calls:
f x1;
f x2;
. . .
f xn
Your problem is mostly that you're missing a semicolon (;) to separate statments that should be done sequentially.
This expression:
f e (iter f q)
is one big expression that calls f with three parameters. You need to separate it into its two parts.
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
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
I have an ocaml type :
type t = A | B | ...
and a function to print things about that type :
let pp_t fmt x = match x with
| A -> Format.fprintf fmt "some nice explanations about A"
| B -> Format.fprintf fmt "some nice explanations about B"
| ...
How could I write a function to print all the explanations ? Something equivalent to :
let pp_all_t fmt =
Format.fprintf fmt A;
Format.fprintf fmt B;
...
but that would warn me if I forget to add a new constructor.
It would be even better to have something that automatically build that function,
because my problem is that t is quiet big and changes a lot.
I can't imagine how I can "iterate" on the type constructors, but maybe there is a trick...
EDIT: What I finally did is :
type t = A | B | ... | Z
let first_t = A
let next_t = function A -> B | B -> C | ... | Z -> raise Not_found
let pp_all_t fmt =
let rec pp x = pp_t fmt x ; try let x = next_t x in pp x with Not_found -> ()
in pp first_t
so when I update t, the compiler warns me that I have to update pp_t and next_t, and pp_all_t doesn't have to change.
Thanks to you all for the advices.
To solve your problem for a complicated and evolving type, in practice I would probably write an OCaml program that generates the code from a file containing a list of the values and the associated information.
However, if you had a function incr_t : t -> t that incremented a value of type t, and if you let the first and last values of t stay fixed, you could write the following:
let pp_all_t fmt =
let rec loop v =
pp_t fmt v;
if v < Last_t then loop (incr_t v)
in
loop First_t
You can't have a general polymorphic incr_t in OCaml, because it only makes sense for types whose constructors are nullary (take no values). But you can write your own incr_t for any given type.
This kind of thing is handled quite nicely in Haskell. Basically, the compiler will write some number of functions for you when the definitions are pretty obvious. There is a similar project for OCaml called deriving. I've never used it, but it does seem to handle the problem of enumerating values.
Since you say you want a "trick", if you don't mind using the unsafe part of OCaml (which I personally do mind), you can write incr_t as follows:
let incr_t (v: t) : t =
(* Please don't use this trick in real code :-) ! See discussion below.
*)
if t < Last_t then
Obj.magic (Obj.magic v + 1)
else
failwith "incr_t: argument out of range"
I try to avoid this kind of code if at all possible, it's too dangerous. For example, it will produce nonsense values if the type t gets constructors that take values. Really it's "an accident waiting to happen".
One needs some form of metaprogramming for such tasks. E.g. you could explore deriving to generate incr_t from the Jeffrey's answer.
Here is a sample code for the similar task : https://stackoverflow.com/a/1781918/118799
The simplest thing you can do is to define a list of all the constructors:
let constructors_t = [A; B; ...]
let pp_all_t = List.iter pp_t constructors_t
This is a one-liner, simple to do. Granted, it's slightly redundant (which gray or dark magic would avoid), but it's still probably the best way to go in term of "does what I want" / "has painful side effects" ratio.