简体   繁体   English

Haskell递归和类型错误

[英]Haskell Recursion and Type Error

I'm teaching myself Haskell and the best way to learn any programming language is to use it. 我正在自学Haskell,学习任何编程语言的最佳方法就是使用它。 My current "exercise" is an implementation of take. 我目前的“练习”是一个实施。 The pseudo-code is: 伪代码是:

take(0, list) = [] --empty list
take(n, list) = const(head(list), take(n-1, tail(list))

What I've worked out in Haskell is: 我在Haskell中得到的结论是:

myTake :: (Num a) => a -> [b] -> [b]
myTake 0 l = []
myTake n (l:ls) = l :  myTake n-1 ls

This doesn't compile when I load the file in GHCi. 当我在GHCi中加载文件时,这不会编译。 This is the error message I get: 这是我收到的错误消息:

Couldn't match expected type `[b]'
       against inferred type `[b1] -> [b1]'
In the second argument of `(:)', namely `myTake n - 1 ls'
In the expression: l : myTake n - 1 ls
In the definition of `myTake':
    myTake n (l : ls) = l : myTake n - 1 ls

My current Haskell resource is "Learn You a Haskell for Great Good!" 我目前的Haskell资源是“为了大好的学习你的Haskell!” and I've read the section on types several times trying to figure this out. 并且我已经多次尝试了关于类型的部分。 Google has been unusually unhelpful too. 谷歌也非常无益。 I think that I don't entirely understand typing yet. 我认为我还没完全理解打字。 Can anyone explain what's going wrong? 任何人都可以解释出了什么问题吗?

myTake n - 1 ls

is parsed like 被解析为

(myTake n) - (1 ls)

because function application binds higher than any infix operator. 因为函数应用程序绑定高于任何中缀运算符。 Parenthesize it: 用括号括起来:

myTake (n - 1) ls

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM