"Error: The function applied to this argument is of type ..." when using named parameters

I am currently working through "Real Word OCaml" and one of the main examples with named / tagged parameters does not work (using utop 4.01.0):

let languages = ["OCaml"; "Perl"; "C"];; List.map ~f:String.length languages;; 

It produces:

 Error: The function applied to this argument has type 'a list -> 'b list This argument cannot be applied with label ~f 

While:

 List.map String.length languages;; 

It produces the expected output [5; 4; 1] [5; 4; 1] [5; 4; 1] .

caml.inria.fr mentions that:

In the main language, as in most languages, the arguments are anonymous.

Does this mean that I have to include some kind of external library for this code to work?

EDIT Here is my ~/.ocamlinit (in accordance with the installation instructions for the book ):

 (* Added by OPAM. *) let () = try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH") with Not_found -> () ;; #use "topfind" #camlp4o #thread #require "core.top" #require "core.syntax" 
+7
named-parameters ocaml utop
source share
2 answers

As mentioned in the @rafix comment, this can be fixed by setting

 open Core.Std ;; 

first.

+6
source share

The standard List.map method is not defined by the ~ f label. The type of List.map is ('a →' b) → 'list →' b list, but if you want to use the label "~ f", it should be "f :(" a → 'b) →' list → 'b list ". If you want to define your own, you must define it as such:

  let rec myMap ~fl = match l with | [] -> [] | h::t -> (fh) :: (myMap ~ft);; val myMap : f:('a -> 'b) -> 'a list -> 'b list = <fun> 

and then you can call it what you like:

  myMap ~f:String.length languages 

Hooray!

+2
source share

All Articles