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

Bul*_* M. 3 haskell haskell-stack

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

试着

(++) <$> ['a'..'z'] <*> ['a'..'z']
Run Code Online (Sandbox Code Playgroud)

但它没有编译.

HTN*_*TNW 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
Run Code Online (Sandbox Code Playgroud)

原因

(++) <$> ['a'..'z'] <*> ['a'..'z']
Run Code Online (Sandbox Code Playgroud)

不起作用是因为你需要(++) :: Char -> Char -> [Char],但你只有(++) :: [Char] -> [Char] -> [Char].你可以在returns参数之上(++)放入Chars 来将s放入单例列表并使事情起作用:

(. return) . (++) . return <$> ['a'..'z'] <*> ['a'..'z']
Run Code Online (Sandbox Code Playgroud)