首页 文章

使用'!!'从List访问Int / Integer元素时出错

提问于
浏览
1

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 回答

  • 2

    索引函数的类型 (!!) 是:

    Prelude> :t (!!)
    (!!) :: [a] -> Int -> a
    

    索引必须是 Int 类型 .

    你有一个类型:

    getRoot::Integer->Integer
    

    您索引的位置 nInteger . 您必须将其转换为 Int 才能用作索引 .

    这可以通过两种方式完成:

    此外,你应该升级到GHC和The Haskell Platform,因为Hugs是一个未经维护的,过时的Haskell版本 .

  • 5

    (!!) 的类型为 [a] -> Int -> a . 如果将 getRoot 的类型签名更改为 Int -> Int ,代码将编译:

    li :: [Int]
    li = [0,1,9,4,9,6,6,7,8,9]
    
    getRoot::Int->Int
    getRoot n | li!!n /= n    = getRoot (li!!n)
    getRoot n | otherwise     = li!!n
    

    测试:

    > getRoot 3
    9
    
  • 1

    (!!)的类型是

    (!!) :: [a] -> Int -> a
    

    换句话说,它接受的第二个参数应该是 Int ,而不是 Integer . 他们是不同的类型 . 如果您更改类型签名以接受 Int ,则此错误将消失 .

    此外,为了使其正常工作, li 必须是 Int 的列表 . 您只需添加类型签名即可完成此操作:

    li :: [Int]
    li = [0,1,9,4,9,6,6,7,8,9]
    

    有了它,一切都应该好 . 祝好运!

相关问题