如何从' aa'中获取字符串。直至' zz'在列表中? 我知道这很明显,但不知道解决这类问题的正确习惯。只要用具体的例子来表达这个想法,我就会弄清楚其余部分。 感谢。
尝试
std::remove_copy(source.begin(), source.end(), std::back_inserter(dest), value);
但它没有编译。
答案 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']