以下是我正在測驗的示例代碼
import Control.Exception
safeLoad :: FilePath -> IO (Either IOException String)
safeLoad f = (Right <$> readFile f) `catch` (pure . Left)
fileChars :: FilePath -> IO (Either IOException Int)
fileChars = fmap (fmap length) . safeLoad
fileChars' :: FilePath -> IO Int
fileChars' = (fmap.fmap) length safeLoad
example :: [Maybe Integer]
example = (fmap.fmap) ( 1) [Just 2,Just 3]
這里的型別(fmap.fmap)評估為:
ghci> :t ((fmap.fmap) length)
((fmap.fmap) length)
:: (Functor f1, Functor f2, Foldable t) =>
f1 (f2 (t a)) -> f1 (f2 Int)
的型別(fmap (fmap ...))也是:
ghci> :t (fmap (fmap length))
(fmap (fmap length))
:: (Functor f1, Functor f2, Foldable t) =>
f1 (f2 (t a)) -> f1 (f2 Int)
但是為什么fileChars'return IO Int while fileCharsreturnIO (Either IOException Int)呢?
uj5u.com熱心網友回復:
因為
fileChars' = (fmap.fmap) length safeLoad
= fmap (fmap length) safeLoad
盡管
fileChars = fmap (fmap length) . safeLoad
注意點。這兩個運算式不等價。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316861.html
標籤:哈斯克尔
上一篇:函式的所有可能值的串列
