[英]Haskell: read and type signatures
read
在Prelude中定义为
read :: (Read a) => String -> a
并且可以用作例如read "1" :: Int
。
现在是一个功能
readOne :: (Read a) => [String] -> (a, [String])
readOne (x:xs) = (read x,xs)
与readOne ["1","foo"]
结果一起使用(如预期的那样)在错误中
Ambiguous type variable 'a' in the constraint:
'Read a' arising from a use of 'readOne' at :1:0-18
Probable fix: add a type signature that fixes these type variable(s)
但readOne ["1","foo"] :: Int
不起作用,而
readOneInt :: [String] -> (Int, [String])
readOneInt = readOne
工作得很好:
> readOneInt ["1", "foo"]
(1,["foo"])
那么:如何在不定义像readOneInt
这样的新函数的情况下为readOne
添加类型签名?
readOne ["1","foo"] :: Int
不起作用,因为readOne
不可能返回Int
,它总是返回一个元组,其第二个元素是[String]
。 readOne ["1", "foo"] :: (Int, [String])
将起作用。
请注意,如果无法推断,则只需指定类型。 如果在需要为Int
的上下文中使用readOne
的结果, readOne
可以使用readOne
而不使用类型注释。 例:
let inc (i, strs) = (i + 1, strs) in
inc (readOne ["1", "foo"])
-- (2, ["foo"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.