【问题标题】:Can't get type signature working for simple recursive function无法使类型签名适用于简单的递归函数
【发布时间】:2013-04-24 05:38:51
【问题描述】:

这是我的代码:

test :: (Num a) => [a] -> a
test []     = 0
test [x:xs] = x + test xs

然而,当我以 :l test 的身份通过 ghci 运行它时,我得到了这个错误:

[1 of 1] 编译 Main(test.hs,解释)

test.hs:3:7:
    Couldn't match type `a' with `[a]'
      `a' is a rigid type variable bound by
          the type signature for spew :: Num a => [a] -> a at test.hs:2:1
    In the pattern: x : xs
    In the pattern: [x : xs]
    In an equation for `spew': spew [x : xs] = x + spew xs
Failed, modules loaded: none.

尽量不要笑 :) 这是我第一次尝试使用 haskell。任何帮助或解释都会很棒。

PS:我知道这可以通过折叠轻松完成,但我正在尝试练习编写自己的类型签名。提前致谢!!

【问题讨论】:

    标签: haskell recursion


    【解决方案1】:

    你是说

    test :: (Num a) => [a] -> a
    test []     = 0
    test (x:xs) = x + test xs -- note round brackets
    

    带圆括号。

    [x:xs] 是一个包含一个元素的列表,它本身就是一个列表,而 (x:xs) 是一个包含第一个元素 x 和尾部 xs 的列表。

    如果你输入length (1:[1,1,1]),你会得到4,但如果你输入length [1:[1,1,1]],你会得到1——唯一的元素是一个列表。

    【讨论】:

    • 呸!!我应该看到的!谢谢!
    • @AthanClark 我们在学习 Haskell 时都会有这种感觉。
    【解决方案2】:

    您可能是要匹配整个列表,而不是列表的第一个元素:

    test (x:xs) = ...
    

    如果您不这样做,则该模式具有推断类型[[b]],因此根据tests 签名,a == [b],因此xs 必须具有类型[b],因此test xs 必须具有类型@987654328 @但还要根据test的签名输入a,这意味着a == [a],这是一个矛盾,导致统一错误:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      相关资源
      最近更新 更多