List Info

Thread: "ocaml_beginners"::[] Cartesian product




"ocaml_beginners"::[] Cartesian product
user name
2006-12-19 05:40:47

Hello,

I'm trying to translate a Haskell function into OCaml and I am stuck.

This is the Haske function:
> cp :: [[a]] -> [[a]]
>; cp [] = [[]]
> cp (xsss) = [y:ys | y <- xs, ys <- cp xss]

And this is one attempt in Ocaml:
let rec cp matrix = match matrix with
| [] -> [[]]
| (xs:ss) -> let rec loop1 a l1 =
let rec loop2 l2 = match l2 with
| [] -> []
| (y::ys) -> (a::y) :: loop2 (cp xss)
| ...

Am I on the right track here or should I be thinking differently?
I don't want to resort to imperative programming.

Any help will be greatly appreciated.

Anders

__._,_.___
.

__,_._,___
"ocaml_beginners"::[] Cartesian product
user name
2006-12-19 06:49:23

On Tue, 19 Dec 2006, Anders Janmyr wrote:

> Hello,
&gt;
> I'm trying to translate a Haskell function into OCaml and I am stuck.
&gt;
> This is the Haske function:
>> cp :: [[a]] -> [[a]]
>;> cp [] = [[]]
>> cp (xsss) = [y:ys | y <- xs, ys <- cp xss]
>
> And this is one attempt in Ocaml:
&gt; let rec cp matrix = match matrix with
> | [] -> [[]]
> | (xs:ss) -> let rec loop1 a l1 =
> let rec loop2 l2 = match l2 with
> | [] -> []
> | (y::ys) -> (a::y) :: loop2 (cp xss)
> | ...
>
> Am I on the right track here or should I be thinking differently?
> I don't want to resort to imperative programming.

Hi Anders,

I would write something like this:

let rec cp = function
[] -> [[]]
| xs :: xss ->
let cpxss = cp xss in
List.flatten
(List.map
(fun y ->
List.map (fun ys -> y :: ys) cpxss)
xs)

It's definitely not easy to read. In addition, you might want to use
List.fold_right instead of List.flatten and List.map, but it makes things
even less clear.

Another option is to use a syntax extension for list comprehensions, such
as pa_compr written by Olivier Andrieu:
http://oandrieu.nerim.net/ocaml/#pa_compr

Martin

--
Martin Jambon, PhD
http://martin.jambon.free.fr

__._,_.___
.

__,_._,___
[1-2]

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