gpt4 book ai didi

haskell - GHCi 中 Applicative 的 pure 的奇怪行为

转载 作者:行者123 更新时间:2023-12-03 21:59:23 25 4
gpt4 key购买 nike

我正在阅读优秀文章 Understanding map and apply通过 Scott Wlaschin 并运行一些 Haskell 代码来理解概念(FunctorApplicative,...)。我偶然发现了一种我不理解的行为。

为什么评估 pure add1 什么都不打印?求值表达式的值是多少?为什么 pure add1 "abc" 返回函数 add1

我理解 pure 将值(value)提升到更高的世界(文章中如此称呼)。由于我没有在某处提供具体的提升值或足够的类型信息,因此类型约束是通用的并且保持 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

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

最佳答案

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

关于haskell - GHCi 中 Applicative 的 pure 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60585478/

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