tags:

views:

130

answers:

1

I am trying to port this haskell function to F#

subs        ::  [a] -> [[a]]
subs []     =   [[]]
subs (x:xs) =   ys ++ map (x:) ys
                where 
                   ys = subs xs

example

subs [1,2,3]

returns:

[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]

returns all sub sequences of a list, which are given by all possible combination of excluding or including each element

....

I am having issues with the 'where' statement, which recursively generates the other list 'ys'.

I am also not sure I port the predicate '(x:)' correctly to '(fun i -> i)'.

This is as much of the F# statement I can figure out.

let rec subs list =
    match list with
        | [] -> [[]]
        | x::xs -> List.map (fun i -> i) xs

Any help or direction would be greatly appreciated.

+7  A: 

Here's the F#:

let rec subs list =    
    match list with        
    | [] -> [[]]        
    | x::xs -> 
        let ys = subs xs
        ys @ List.map (fun t -> x::t) ys

printfn "%A" (subs [1;2;3])

A Haskell where is pretty much just like a let moved to the bottom.

In F#, @ is the list concatenation operator, and :: is cons.

There are no operator sections in F#, so I use a lambda (fun).

Brian
I knew you'd get in before me...one of these days you'll be in a meeting or something and I'll beat you to the punch! =) Great answer as always.
Ray Vernagus
I got lucky; some intranet IT update is about to force me to reboot right now :)
Brian