Given a set represented as a String
, we can compute its powerset using foldLeft
, as shown below.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def powerset(s: String) = | |
s.foldLeft(Set("")) { | |
case (acc, x) => acc ++ acc.map(_ + x) | |
} |
Isn’t this approach quite concise and elegant? Following snippet shows a pretty-printed output from powerset
for a set: "abc"
.
scala> powerset("abc").toList sortWith ( _ < _) mkString "\n"
res3: String = "
| a
| ab
| abc
| ac
| b
| bc
| c"
Following is a F# implementation of this same function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let powerset (s:string): Set<string> = | |
s.ToCharArray() | |
|> Array.fold( | |
fun (acc: Set<string>) x -> acc + (Set.map(fun y -> x.ToString()+y) acc) | |
) (Set.empty.Add("")) |