Haskell/理解单子/解决方案/列表
外观
1.
Prelude> ["bunny", "rabbit"] >>= generation
["bunny","bunny","bunny","rabbit","rabbit","rabbit"]
每个元素都会产生三个自己的副本。副本的顺序与原始元素的顺序相同。
2.
themselvesTimes :: [Int] -> [Int]
themselvesTimes ns = ns >>= \n -> replicate n n
1.
(<*>)
用于列表,它接受一个函数列表和一个可以传递给这些函数的值列表。然后,它将每个函数应用于所有值,并将所有生成的結果放在单个列表中返回。
2.
fs <*> xs = [ f x | f <- fs, x <- xs ]
请注意,在编写上面的列表推导式时,生成器的顺序很重要。为了看到区别,请在 GHCi 中尝试 (\fs xs -> [ f x | f <- fs, x <- xs ]) [(2*),(3*)] [1,2]
和 (\fs xs -> [ f x | x <- xs, f <- fs ]) [(2*),(3*)] [1,2]
。