开发者

Haskell map function with where statement in F#

开发者 https://www.devze.com 2022-12-14 05:01 出处:网络
I am trying to port this haskell function to F# subs::[a] -> [[a]] subs []=[[]] subs (x:xs) =ys ++ map (x:) ys

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 i开发者_如何学JAVAs 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.


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).


Let's get it to look more like F#. :)

let rec subs = function
| [] -> [[]]
| x::xs -> [ for ys in subs xs do
                yield! [ys;x::ys] ]
0

精彩评论

暂无评论...
验证码 换一张
取 消