gpt4 book ai didi

haskell - haskell中的递归实例

转载 作者:行者123 更新时间:2023-12-01 22:22:38 26 4
gpt4 key购买 nike

当使用下面的代码时,我得到下面关于 toInt 的递归使用的错误消息

module Intro0 where
data Zero
data Succ n

class Nat n where
toInt :: n -> Int
instance Nat Zero where
toInt _ = 0
instance (Nat n) => Nat (Succ n) where
toInt _ = (1::Int) + toInt (undefined :: n)

我原以为发现 toInt 是微不足道的,因为它是在递归实例的上下文中指定的,但我遇到了统一问题

Could not deduce (Nat n0) arising from a use of ‘toInt’
from the context (Nat n)
bound by the instance declaration
at EPhantomTypes.hs:10:10-32
The type variable ‘n0’ is ambiguous
Note: there are several potential instances:
instance Nat n => Nat (Succ n)
-- Defined at EPhantomTypes.hs:10:10
instance Nat Zero
-- Defined at EPhantomTypes.hs:8:10
In the second argument of ‘(+)’, namely ‘toInt (undefined :: n)’
In the expression: (1 :: Int) + toInt (undefined :: n)
In an equation for ‘toInt’:
toInt _ = (1 :: Int) + toInt (undefined :: n)

我不知道这是为什么。它看起来微不足道,但我不确定如何处理它。

显然 nn0 应该相同,但即使使用

instance forall n . (Nat n) => Nat (Succ n) where

导致相同的错误信息

最佳答案

问题与变量 n 的范围有关。特别是,(undefined::n) 中的 n(Nat n) => 中的 n 不同Nat(成功 n)。如果您想更改此设置,可以启用 -XScopedTypeVariables (或将 {-# LANGUAGE ScopedTypeVariables #-} 添加到文件的顶部),然后两个 n 将相同,所有内容都将编译。

关于haskell - haskell中的递归实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39013007/

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