【问题标题】:Haskell type inference with Read使用 Read 进行 Haskell 类型推断
【发布时间】:2012-11-13 09:16:42
【问题描述】:

我认为 Haskell 类型推断有问题。

我创建了自己的数据类型并将其作为Read 类的实例。我的数据类型其实是取另一个类型作为参数,它是一个类型参数。

我重新定义了readPresc,以解析字符串并返回我的新数据。当我写:

read "string that represent MyType a" :: MyType a

它工作得非常好(至少它达到了我的预期)

现在我有一个函数,我们称之为insert,它接受aMyType a 类型的元素,并返回一个新的MyTape a

insert :: a -> MyType a -> a

但是当我写的时候:

insert 3 "string that rapresent MyType Int" 

我收到了Ambigous type

如何告诉haskell 推断read 与插入参数的类型相同?

【问题讨论】:

  • 你的意思是insert 3 (read "string representation")
  • 另外,你能澄清一下吗? read "bla blah blah" :: MyType 暗示 MyType 是一个类型,但 insert :: a -> MyType a -> a 暗示 MyType 是一个类型构造函数。

标签: haskell type-inference


【解决方案1】:

如何告诉haskell 推断read 与插入参数的类型相同?

你不需要,那是从insert的类型推断出来的。

问题在于

insert 3 (read "string that rapresent MyType Int" )

(我插入了 read 以使其类型可能正确),文字 3 是多态的。它的类型是

3 :: Num a => a

所以仍然没有足够的信息来确定read 应该产生什么类型,因此会出现错误。

您需要提供必要的信息,例如

insert (3 :: Int) (read "string that rapresent MyType Int" )

或者通过在确定类型变量a的上下文中使用结果。

【讨论】:

    猜你喜欢
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 2011-02-22
    相关资源
    最近更新 更多