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.
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] ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.