gpt4 book ai didi

haskell - (fmap.fmap) func 与 fmap (fmap func) 的返回类型

转载 作者:行者123 更新时间:2023-12-01 23:13:12 28 4
gpt4 key购买 nike

下面是我正在测试的示例代码

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' 返回 IO IntfileChars 返回 IO (Either IOException Int)

最佳答案

因为

fileChars' = (fmap.fmap) length safeLoad
= fmap (fmap length) safeLoad

同时

fileChars = fmap (fmap length) . safeLoad

注意点。这两个表达式是等价的。

关于haskell - (fmap.fmap) func 与 fmap (fmap func) 的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69432210/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com