简体   繁体   中英

F# set to list with set.fold

I'm programming in F# and I'm trying to make a set into a list by using Set.fold.

What I've done so far:

let list sa = Set.fold (fun se sa -> sa) [];;

but it doesn't seem to make the set into a list, rather it makes a set of lists into a list.

What change can I make to my code so it won't make a set of lists into a list, but a set into a list.

let toList s = Set.fold (fun l se -> se::l) [] s

1st argument of fold is the function taking two parameters: accumulator of type that should be returned from fold ( list in your case), and a single element of collection fold applies to (element of Set in your case). This function should return the type same of accumulator passed as the 1st parameter ( list in your case). So the function should add current element of the set to list accumulator.

2nd parameter of fold is the initial accumulator state (empty list in your case).

3rd parameter of fold in your case is the Set you want to transform to list

Using Set.fold you will receive the items in reverse order:

let list sa =  sa |> Set.fold (fun se sacc -> sacc::se) [] |> List.rev

Or, use Set.foldBack:

let list2 sa =  Set.foldBack (fun se sacc -> se::sacc) sa []

Example:

let list sa =  sa |> Set.fold (fun se sacc -> sacc::se) [] |> List.rev
let list2 sa =  Set.foldBack (fun se sacc -> se::sacc) sa []

let set = [1 ; 12; 6 ;8 ; 4] |> Set.ofList

set |> printfn "%A"

list set |> printfn "%A"
list2 set |> printfn "%A"

Print:

set [1; 4; 6; 8; 12]
[1; 4; 6; 8; 12]
[1; 4; 6; 8; 12]

Link:

https://dotnetfiddle.net/xwLMIp

PS There is a standard function Set.toList

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM