Level of Haskell :新手
Goal :查找表示为List的树的元素的根
Input (Tree Nodes) (Positions in Array denote the node number) :[0,1,9,4,9,6,6,7,8,9]
Function invoked :getRoot 3
Expected Output :9
Code :
li = [0,1,9,4,9,6,6,7,8,9]
getRoot::Integer->Integer
getRoot n | li!!n /= n = getRoot li!!n
getRoot n | otherwise = li!!n
Error Message :
ERROR file:.\test2.hs:111 - Type error in application
*** Expression : li !! n
*** Term : n
*** Type : Integer
*** Does not match : Int
Compiler :WinHugs
尝试了'Integers'和'Int'的各种组合来声明函数的类型 . 似乎数组访问返回一个Integer,但然后与它失败的Int进行比较 . 不知道为什么它不将Int转换为Integers .
或者它是一起的其他东西?
在互联网上,在教程和stackoverflow上搜索 .
3 回答
索引函数的类型
(!!)
是:索引必须是
Int
类型 .你有一个类型:
您索引的位置
n
是Integer
. 您必须将其转换为Int
才能用作索引 .这可以通过两种方式完成:
转换使用
fromInteger
使用genericIndex
此外,你应该升级到GHC和The Haskell Platform,因为Hugs是一个未经维护的,过时的Haskell版本 .
(!!)
的类型为[a] -> Int -> a
. 如果将getRoot
的类型签名更改为Int -> Int
,代码将编译:测试:
(!!)的类型是
换句话说,它接受的第二个参数应该是
Int
,而不是Integer
. 他们是不同的类型 . 如果您更改类型签名以接受Int
,则此错误将消失 .此外,为了使其正常工作,
li
必须是Int
的列表 . 您只需添加类型签名即可完成此操作:有了它,一切都应该好 . 祝好运!