gpt4 book ai didi

haskell - 如何解释这个类型检查的 Haskell 代码?

转载 作者:行者123 更新时间:2023-12-04 23:41:14 24 4
gpt4 key购买 nike

读书Haskell Programming from First Principles ,我在第 6 章“类型类”中遇到了以下练习:

-- Hint: use some arithmetic operation to
-- combine values of type 'b'. Pick one.
arith :: Num b => (a -> b) -> Integer -> a -> b
arith = ???

我想出了以下解决方案,我将其称为“解决方案”,因为它可以编译:
arith f _ x = f x

但是我有点困惑如何“解释”我上面刚刚写的内容。我对 arith 类型签名的“阅读”是这样的:

arith takes one function, one Integer, a parameter of type a, and returns a result that is of type b; moreover, the function that arith takes as the first parameter is a function that takes a parameter of type a and returns a value of type b, and that value has to be of type b whose typeclass is (or 'constrained') by Num.



在那之后,我想出了上面的“解决方案”,但我没有使用“一些算术运算来组合 'b' 类型的值”。不知何故,我认为“提示”要么具有误导性,要么完全没问题,我错过了一些东西,如果是这样,那我错过了什么?

最佳答案

我认为预期的解决方案是:

arith f i a = f a + fromInteger i

或与 + 之一替换为 -* .

回顾一下要求:在本练习中,您必须实现一个函数:
  • 匹配类型签名 arith :: Num b => (a -> b) -> Integer -> a -> b .
  • 使用算术运算来组合 b 类型的值.

  • 您将获得三个类型 (a -> b) 的值, Integera .作为第一步,您需要将它们转换为 b 类型的两个值。 .您可以通过申请 (a -> b) 获得第一个至 a .然后你就剩下了 Integer 类型的值.当您 notice类型类的实例 Num支持功能 fromInteger :: Integer -> a (其中类型 a 是类型 b 在我们定义的函数上下文中),很明显您可以获得类型 b 的第二个值通过申请 fromInteger给您的 Integer值(value)。第二步,组合 b 类型的两个值使用 Num 中定义的算术运算之一类型类。

    关于haskell - 如何解释这个类型检查的 Haskell 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37244341/

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