我正在编写一个函数来生成一组字符串的所有排列——“foo”应该返回 {“foo”、“ofo”、“oof”}。我已经在 Clojure 中这样做了,所以我知道这种方法是正确的,但我想我会在 Haskell 中进行练习。下面是我所拥有的。
import qualified Data.Set as Set
substr :: String -> Int -> Int -> String
substr s start end = take (end - start) . drop start $ s
substrs :: String -> Set.Set (Char, String)
substrs s = let len = length s
in foldl (\acc x -> Set.insert (s !! x, ((substr s 0 x)++(substr s (succ x) len))) acc) Set.empty [0..len-1]
-- not sure about the type
permute [] = Set.empty
permute s = Set.map recurFunc (substrs s)
where recurFunc (c, s) = Set.map (c:) (permute s)
main :: IO ()
main = print $ permute "foo!"
当然,这不会编译,否则我不会问。我得到:
permute.hs:12:21:
Couldn't match expected type `String'
with actual type `Set.Set [Char]'
Expected type: (Char, String) -> String
Actual type: (Char, String) -> Set.Set [Char]
In the first argument of `Set.map', namely `recurFunc'
In the expression: Set.map recurFunc (substrs s)
Set.map
被声明为(a -> b) -> Set a -> Set b
。据我所知,recurFunc
接受一组(Char, String)
对,并返回一组字符串。substrs
返回一组(Char, String)
对。那么这怎么不一致呢?