如何获得字符串' aa',ab'直至' yz',' zz'?

时间:2017-11-18 06:33:10

标签: haskell haskell-stack

如何从' aa'中获取字符串。直至' zz'在列表中? 我知道这很明显,但不知道解决这类问题的正确习惯。只要用具体的例子来表达这个想法,我就会弄清楚其余部分。 感谢。

尝试

std::remove_copy(source.begin(), source.end(), std::back_inserter(dest), value);

但它没有编译。

1 个答案:

答案 0 :(得分:6)

所有这些都做你想要的(记住String = [Char]):

Control.Monad.replicateM 2 ['a'..'z'] -- Cleanest; generalizes to all Applicatives
sequence $ replicate 2 ['a'..'z'] -- replicateM n = sequenceA . replicate n
-- sequence = sequenceA for monads
-- sequence means cartesian product for the [] monad

[[x, y] | x <- ['a'..'z'], y <- ['a'..'z']] -- Easiest for beginners
do x <- ['a'..'z']
   y <- ['a'..'z']
   return [x, y] -- For when you forget list comprehensions exist/need another monad
['a'..'z'] >>= \x -> ['a'..'z'] >>= \y -> return [x, y] -- Desugaring of do
-- Also, return x = [x] in this case
concatMap (\x -> map (\y -> [x, y]) ['a'..'z']) ['a'..'z'] -- Desugaring of comprehension
-- List comprehensions have similar syntax to do-notation and mean about the same,
-- but they desugar differently

(\x y -> [x, y]) <$> ['a'..'z'] <*> ['a'..'z'] -- When you're being too clever
(. return) . (:) <$> ['a'..'z'] <*> ['a'..'z'] -- Same as ^ but pointfree

原因

(++) <$> ['a'..'z'] <*> ['a'..'z']

不起作用是因为您需要(++) :: Char -> Char -> [Char],但您只有(++) :: [Char] -> [Char] -> [Char]。您可以在returns的参数之上放入(++)以将Char放入单例列表中并使其起作用:

(. return) . (++) . return <$> ['a'..'z'] <*> ['a'..'z']