通常没有unwrap 这样的东西,考虑f 是列表函子[] unwrap 应该为[_, _, _] 或更好的空列表[] 返回什么?与Maybe 类似,假设h 是const Nothing,你会期望得到Nothing。但是在尝试将unwrap 和Nothing 转换为值a 时,您的思路将失败。您会注意到,尝试应用pure(将结果重新打包到函子中)意味着您希望Maybe函子的结果始终为Just,[]等的结果为非空。
对于读者函子((->) k) 而言,Traversable 实例几乎没有希望。虽然这不是证据,但在这个方向上的一个很好的证据是Prelude 中缺少这样的实例。此外,要遍历函数并生成最终容器([] 或 Maybe),您需要将函数 h 应用于函数的任何可想到的输出,即很多潜在值,通常是无限多的。
Prelude> traverse (\n -> if n == 42 then Nothing else Just n) [1, 2, 3]
Just [1,2,3]
Prelude> traverse (\n -> if n == 42 then Nothing else Just n) [1..]
Nothing
假设k是Int,所以函子是Int ->,假设你有一个值g :: Int -> Int,让它是\n -> if n == 42 then 0 else n,假设你想用上面的函数遍历那个值,那如果g 为任何输入输出42,则遍历将是Nothing,但事实并非如此。遍历无法知道这一点(它无法访问函数的代码),因此它必须尝试所有输出。
如果k 是有限的,那么您可以通过制表来遍历函数。遍历表后,您可能会产生结果。这可能不是您所追求的,但是:
import Data.Char
import Data.Maybe
import Data.Word
instance ( Enum k, Bounded k ) => Foldable ((->) k) where
foldMap h f = foldMap (h . f) domain
instance ( Enum k, Bounded k, Eq k ) => Traversable ((->) k) where
traverse h f = fmap (\vs k -> fromJust $ k `lookup` zip domain vs) (traverse (h . f) domain)
domain :: ( Enum k, Bounded k ) => [k]
domain = enumFromTo minBound maxBound
tabulate :: ( Enum k, Bounded k ) => (k -> a) -> [(k, a)]
tabulate f = zip domain (map f domain)
f1 :: Bool -> Int
f1 b = if b then 42 else 666
f2 :: Ordering -> Char
f2 LT = 'l'
f2 EQ = 'e'
f2 GT = 'g'
f3 :: Word8 -> Bool
f3 n = fromIntegral n < 256
f4 :: Word16 -> Bool
f4 n = fromIntegral n < 256
main = do
print (tabulate f1)
print (tabulate <$> traverse (\n -> [n, 2*n]) f1)
putStrLn ""
print (tabulate f2)
print (tabulate <$> traverse (\c -> [c, toUpper c]) f2)
putStrLn ""
print (tabulate f3)
print (tabulate <$> traverse (\b -> if b then Just b else Nothing) f3)
putStrLn ""
print (tabulate <$> traverse (\b -> if b then Just b else Nothing) f4)