λ> import Data.Traversable
λ> let qs = ["name", "quest", "favorite color"]
λ> traverse (\thing -> putStrLn ("What is your " ++ thing ++ "?") *> getLine) qs
What is your name?
Sir Lancelot
What is your quest?
to seek the holy grail
What is your favorite color?
blue
["Sir Lancelot","to seek the holy grail","blue"]
data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
Tree的 Functor实例应该是:
instance Functor Tree where
fmap f Empty = Empty
fmap f (Leaf x) = Leaf (f x)
fmap f (Node l k r) = Node (fmap f l) (f k) (fmap f r)
它重新构建整个树,对每个值应用 f。
instance Traversable Tree where
traverse f Empty = pure Empty
traverse f (Leaf x) = Leaf <$> f x
traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
For historical reasons, the Traversable class also contains a monadic version of traverse called mapM. For all intents and purposes mapM is the same as traverse - it exists as a separate method because Applicative only later became a superclass of Monad.
循环。它的实现取决于要遍历的数据结构。这可能是一个列表、树、 Maybe、 Seq(uence) ,或者任何通过 for 循环或递归函数来遍历的通用方法。一个数组应该有一个 for 循环,一个列表,一个 while 循环,一个树,或者一些递归的东西,或者堆栈和 while 循环的组合; 但是在函数式语言中,你不需要这些繁琐的循环命令: 你可以用一种更直接的方式将循环的内部部分(以函数的形式)与数据结构结合起来,减少冗长。