我正在写一个函数来产生一组字符串的所有排列 - “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)
对。那么这是如何不一致?
我建议先开始使用基于列表的版本,然后调整它以便稍后使用“设置”,如果您决定真的需要它。列表不那么令人困惑(并且无论如何,对于像这样的少量数据来说'Set'并不是一个更快的事情)。 – 2013-04-10 03:41:52