Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Recursive apply function
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Brian Hurt <bhurt@s...>
Subject: Re: [Caml-list] Recursive apply function
On Wed, 19 Nov 2003, Peter Scott wrote:

> I'm having an interesting disagreement with ocaml about types. I'm trying 
> to make a function to imitate the lisp apply function. That is, I want to 
> make a function which will apply another function to a list.
> 
> I came up with this code:
> 
> let rec apply f args =
>    match args with
>        arg :: rest -> apply (f arg) rest
>      | [] -> f;;

This is untypeable.  What's the type of f?  It's a function that takes a 
'a and returns a function which takes a type 'a and returns a function 
which takes a type 'a and returns a function which takes a type 'a and 
etc.

What you want is List.fold_left, which has type:
('a -> 'b -> 'a) -> 'a -> 'b list -> 'a

and can be implemented as:

let rec fold_left f init_val = function
	| [] -> init_val
	| h :: t -> fold_left f (f init_val h) t
;;

But don't reimplement it, use the library version.

> 
> let add x y = x + y;;
> let x = apply add [2; 3];;
> print_int x;;

let x = List.fold_left (+) 0 [2; 3];;

You don't need to define a special add function.

-- 
"Usenet is like a herd of performing elephants with diarrhea -- massive,
difficult to redirect, awe-inspiring, entertaining, and a source of
mind-boggling amounts of excrement when you least expect it."
                                - Gene Spafford 
Brian

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners