在 GHCi 中从 Applicative 纯的奇怪行为

Lud*_*uty 4 haskell ghci applicative

我正在阅读Scott Wlaschin撰写的《理解地图和应用》的优秀文章并运行一些 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
Run Code Online (Sandbox Code Playgroud)

编辑 我认为@chi 的两条评论和@sarah 的回答回答了这个问题,因为它显示了 GHCi 选择的应用程序来评估表达式并解释了观察到的行为。

sar*_*ara 5

由于您将表达式pure add1应用于值"abc",因此 Applicative 实例被选为 for 的实例(->) String。在那个实例中,pure = const,所以你的最终表达式是const add1 "abc"which is add1,它没有 Show 实例!