gpt4 book ai didi

haskell - 在 Haskell 中的元组和列表上 Applicative 的不同行为

转载 作者:行者123 更新时间:2023-12-05 00:20:39 27 4
gpt4 key购买 nike

例如,

-- Num a => ([Char], a -> a) <*> ([Char], a)
> ("hello ",(*6)) <*> ("world",7)
("hello world",42)

-- Num a => [a -> a] <*> [a]
> [(*7),(*6)] <*> [6,7]
[42,49,36,42]

-- Num a => [[Char], a -> a] <*> [[Char], a]
> ["hello ",(*6)] <*> ["world",7]
<interactive>:17:2:
Couldn't match expected type ‘[Char] -> [Char]’
with actual type ‘[Char]’
In the expression: "hello "
In the first argument of ‘(<*>)’, namely ‘["hello ", (* 6)]’
In the expression: ["hello ", (* 6)] <*> ["world", 7]

对于三个示例, <*>表现出不同的行为。发生什么了?为什么在第三种情况下,它期望 [Char] -> [Char]而不是 [Char]就像在第一种情况下一样。更何况,竟然只有 [Char]在元组中, <*>将它们结合在一起。

最佳答案

区别在于列表是同构的,而元组不是:列表仅包含相同类型的元素,而元组则不必。

即使不看应用程序,仿函数也已经显示出主要区别:

fmap succ [1,2,3]  ==> [2,3,4]
fmap succ ("a", 4) ==> ???

认为 fmap 是不合逻辑的。适用 succ"a" .发生的情况是只有第二个组件受到影响:
fmap succ ("a", 4) ==> ("a", 5)

确实,看看实例:
instance Functor [] where ...
instance Functor ((,) a) where ...

请注意 a类型。在列表实例中, []只接受一个类型参数,那就是受 fmap 影响的类型.在 (,)我们有两种类型参数:一种是固定的(到 a )并且在应用 fmap 时不会改变——只有第二个可以。

请注意,理论上可以允许 Functor (,) 的实例。当两个类型参数被强制相同时。例如。,
instance Functor (\b -> (b,b)) where ...

但是 Haskell 不允许这样做。如果需要,需要一个 newtype 包装器:
newtype P b = P (b,b)
instance Functor P where
fmap f (P (x,y)) = P (f x, f y)

关于haskell - 在 Haskell 中的元组和列表上 Applicative 的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852781/

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