gpt4 book ai didi

haskell - 在 ZipList 中实现 `pure`

转载 作者:行者123 更新时间:2023-12-01 07:18:41 25 4
gpt4 key购买 nike

Typeclassopedia提出这个问题:

Determine the correct definition of pure for the ZipList instance of Applicative—there is only one implementation that satisfies the law relating pure and (<*>).



我不确定如何直接解决它,所以我在 ghci中测试了它:
ghci> pure 5 :: ZipList Int
ZipList {getZipList = [5,5,5,5,5,5,5,5,5,5,5,5,5, ...

哪里 ...意味着无尽 5的。

为什么以这种方式实现 - 生成一个没有尽头的列表?

最佳答案

以应用仿函数的恒等律为例

pure id <*> v = v                            -- Identity

在 ZipList 的上下文中,我们通过应用 <*> 左侧的每个函数来生成输出。通过其右侧的相应值....
ZipList [f1, f2, f3, ....] <*> ZipList [v1, v2, v3, ....] = 
ZipList [f1 v1, f2 v2, f3 v3, ....]

所以,因此,得到 v回来,我们需要左边的每个函数都是 id .
pure id = [id, id, id, ....]

如果左侧是单个函数 [id] ,右侧将只有一项长。

关于haskell - 在 ZipList 中实现 `pure`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27220933/

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