【问题标题】:Couldn't match expected type Int against inferred type Integer无法将预期类型 Int 与推断类型 Integer 匹配
【发布时间】:2012-10-28 22:15:35
【问题描述】:

我编写了一些简单的haskell 函数来计算图中给定顶点的邻居(见下文)。它编译得很好,但是,当我运行 adj g 1 时,我收到以下错误:Couldn't match expected type `Int' against inferred type `Integer'

代码:

module Test where
import Prelude
import Data.List


type Node = Int
type Edge = (Int, Int)

type Graph = ([Node], [Edge])

g = ([1,2,3,4,5,6], [(1,2),(2,3),(2,4),(5,6)])


adj :: Graph -> Node -> [Node]
adj (vs, []) n = []
adj (vs,((s,e):es)) n   | s==n = e:rec
                        | e==n = s:rec
                        | otherwise = rec
    where
    rec = adj (vs,es) n 

【问题讨论】:

    标签: haskell inferred-type


    【解决方案1】:

    添加显式类型签名:

    g :: ([Int], [(Int, Int)])
    

    或者更好

    g :: Graph
    

    发生这种情况是因为像 7 这样的数字可以是任何整数类型,并且它默认为 Integer,而您的函数使用 Int。

    【讨论】:

    • 你能不写g :: Graph吗?
    • @DanielBuckmaster 我不能写什么吗?
    • 是的,我在你写的时候把它弹出来了!
    • 嘿,对不起,不记得按回车键发表了评论。好的,酷!
    • 当我在手机上使用 SO 时,您不会相信这种情况发生的频率有多高。太令人沮丧了。
    猜你喜欢
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多