List Info

Thread: Re: "ocaml_beginners"::




Re: "ocaml_beginners"::
country flaguser name
United Kingdom
2007-08-19 12:50:16

[repost: something strange is going on with yahoo groups]

On Sat, Aug 18, 2007 at 08:39:25PM +0200, Fabrice Marchant wrote:
> (* All right above.
> But when I try to unify/compact all these repetead things below, there is a compile error : *)
>
> let rec lists_product f =
> function
> [] ->
> f
> | h::t ->
> List.iter
> (fun e -> lists_product (f e) t)
> (* ^^^^^
> This expression has type 'a but is here used with type 'b -> 'a *)

As far as I understand it, you want a higher-order function, let's
call it 'anylist_iter' which applies a function f to any list, list of
lists, list of list of lists and so on. So:

anylist_iter f [1]
anylist_iter f [[1;2]; [3;4]]
anylist_iter f [[[1;2]; [3;4]]; [[5];[6]]]

You cannot write such a function in a statically typed language
(although you can write it unsafely with a bit of Obj.magic). To
understand why this isn't possible, ask yourself what would be the
type of such a function?

anylist_iter : ('a -> unit) -> 'a list -> unit
anylist_iter : ('a -> unit) -> 'a list list -> unit
anylist_iter : ('a -> unit) -> 'a list list list -> unit

(A function can only have one type, but it would need all 3 types
above, and more, to operate in the general case).

> let _ = lists_product
> (fun x y z -> Printf.printf "(%i, %i, %i) " x y z)
> [[1; 3; 5]; [2; 4]; [10; 100]]

You can write something like this:

# List.iter (fun xs ->
print_endline (String.concat ","
(List.map string_of_int xs)))
[[1; 3; 5]; [2; 4]; [10; 100]];;
1,3,5
2,4
10,100

Rich.

--
Richard Jones
Red Hat

__._,_.___
.

__,_._,___
[1]

about | contact  Other archives ( Real Estate discussion Medical topics )