我正在阅读Scott Wlaschin的出色文章Understanding map and apply,并运行一些Haskell代码以了解概念(Functor
,Applicative
,..)。我偶然发现了我不了解的行为。
为什么评估pure add1
什么都不打印?求值表达式的值是多少?为什么pure add1 "abc"
还给我函数add1
?
[我了解pure
将价值带入高尚的世界(在本文中称为)。由于我没有在某处提供具体的提升值或足够的类型信息,因此类型约束是通用的,并且保持Applicative f
。因此,我了解pure add1
的类型。但是这里发生的其余事情使我难以理解。
$ stack ghci
GHCi, version 8.8.2
λ: add1 :: Int -> Int ; add1 x = x + 1
λ: :t add1
add1 :: Int -> Int
λ: add1 100
101
λ: :t pure
pure :: Applicative f => a -> f a
λ: pure add1
λ: :t pure add1
pure add1 :: Applicative f => f (Int -> Int)
λ: pure add1 "abc"
<interactive>:8:1: error:
• No instance for (Show (Int -> Int)) arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In a stmt of an interactive GHCi command: print it
λ: :t pure add1 "abc"
pure add1 "abc" :: Int -> Int
λ: pure add1 "abc" 100
101
由于将表达式pure add1
应用于值"abc"
,因此,“适用”实例被选为(->) String
的实例。在这种情况下,为pure = const
,因此您的最终表达式为const add1 "abc"
,即add1
,没有Show实例!