Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm currently working through "Real Word OCaml", and one of the basic examples with named / labeled parameters doesn't seem to work (using utop 4.01.0):

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

Produces:

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

Whereas:

List.map String.length languages;;

Produces the expected output [5; 4; 1].

caml.inria.fr mentions that:

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

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

EDIT Here's my ~/.ocamlinit file (as per 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" 
like image 629
Frank Schmitt Avatar asked Feb 01 '14 13:02

Frank Schmitt


2 Answers

As mentioned in @rafix's comment, this can be fixed by putting

open Core.Std ;;

first.

like image 113
Frank Schmitt Avatar answered Nov 14 '22 19:11

Frank Schmitt


The standard List.map method isn't defined with the label ~f. The type of List.map is ('a -> 'b) -> 'a list -> 'b list, but if you wanted to use the "~f" label, it would have to be "f:('a->'b) -> 'a list -> 'b list". If you wanted to define your own, you would have to define it as such:

 let rec myMap ~f l = match l with
 | [] -> []
 | h::t -> (f h) :: (myMap ~f t);;

 val myMap : f:('a -> 'b) -> 'a list -> 'b list = <fun>

and then you could call it like you wanted:

 myMap ~f:String.length languages

Cheers!

like image 41
sacooper93 Avatar answered Nov 14 '22 17:11

sacooper93