错误“No instance for(Num [t])”在Collat​​z功能 [英] Error "No instance for (Num [t])" in Collatz function

查看:113
本文介绍了错误“No instance for(Num [t])”在Collat​​z功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Haskell的新手,一般编程。我试图定义一个从 n 生成Collat​​z数字序列的函数。我有:

  collat​​z n =(collat​​z'n):1 
其中collat​​z'n =(takeWhile(> ; 1)(collat​​z''))
其中collat​​z''n = n:collat​​z''(collat​​z'''n)
其中collat​​z'''1 = 1
collat​​z' ''n = if(even n)then(div n 2)else((3 * 2)+1)

当我在GHCi中运行这个时,我得到错误:

$ p $ 没有实例用于(Num [t])$在< interactive>:1:7
的文字'2'产生的b $ b可能的修正:为(Num [t])
pre>

我不知道这是什么意思。问题似乎在列表中追加1。出现这个问题的原因是

pre $ collat​​z'n =(takeWhile(> 0)(collat​​z''n))

在正确的Collat​​z序列之后生成无限序列的1;然而,

  collat​​z'n =(takeWhile(> 1)(collat​​z''n))
code>

会从 n 生成除1以外的所有Collat​​z数字。我做错了什么?

解决方案

ony的回答是正确的,但是因为你是Haskell的新手,也许这是一个更清晰的说明。 运算符 pre 将值赋予一个列表,所以 somelist:7 是无效,因为它试图将值存入列表。这就是为什么(collat​​z'n):1 不能编译的原因,因为(collat​​z'n)的类型是尝试用 ++ [1]替换:1


I am new to Haskell, and programming in general. I am trying to define a function which generates the sequence of Collatz numbers from n. I have:

collatz n = (collatz' n) : 1
   where collatz' n = (takeWhile (>1) (collatz'' n))
          where collatz'' n = n : collatz'' (collatz''' n)
                 where collatz''' 1 = 1
                       collatz''' n = if (even n) then (div n 2) else ((3*2)+1)

When I run this in GHCi, I get the error:

No instance for (Num [t])
  arising from the literal `2' at <interactive>:1:7
Possible fix: add an instance declaration for (Num [t])

I don't know what this means. The problem seems to be appending "1" to the list. This problem emerges because

collatz' n = (takeWhile (>0) (collatz'' n))

generates an infinite sequence of "1"s following the correct Collatz sequence; however,

collatz' n = (takeWhile (>1) (collatz'' n))

generates all Collatz numbers from n except "1". What am I doing wrong?

解决方案

ony's answer is correct, but since you're new to Haskell, maybe this is a clearer explanation. The : operator prepends a value to a list, so doing somelist : 7 is invalid since that's trying to append a value to a list. That's why (collatz' n) : 1 doesn't compile, since the type of (collatz' n) is a list of numbers.

Try replacing the : 1 with ++ [1].

这篇关于错误“No instance for(Num [t])”在Collat​​z功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆