[英]Haskell: read and type signatures
read
is defined in the Prelude as read
在Prelude中定义为
read :: (Read a) => String -> a
and can be used as eg read "1" :: Int
. 并且可以用作例如
read "1" :: Int
。
Now a function 现在是一个功能
readOne :: (Read a) => [String] -> (a, [String])
readOne (x:xs) = (read x,xs)
used with readOne ["1","foo"]
results (as expected) in the error 与
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)
But readOne ["1","foo"] :: Int
doesn't work, while 但
readOne ["1","foo"] :: Int
不起作用,而
readOneInt :: [String] -> (Int, [String])
readOneInt = readOne
works just fine: 工作得很好:
> readOneInt ["1", "foo"]
(1,["foo"])
So: how can I add a type signature to readOne
without defining a new function like readOneInt
? 那么:如何在不定义像
readOneInt
这样的新函数的情况下为readOne
添加类型签名?
readOne ["1","foo"] :: Int
doesn't work because readOne
couldn't possibly return an Int
, it always returns a tuple, whose second element is a [String]
. readOne ["1","foo"] :: Int
不起作用,因为readOne
不可能返回Int
,它总是返回一个元组,其第二个元素是[String]
。 readOne ["1", "foo"] :: (Int, [String])
will work. readOne ["1", "foo"] :: (Int, [String])
将起作用。
Note that you only need to specify the type if it can't be inferred. 请注意,如果无法推断,则只需指定类型。 If you use the result of
readOne
in a context where it needs to be an Int
, you can use readOne
without type annotations. 如果在需要为
Int
的上下文中使用readOne
的结果, readOne
可以使用readOne
而不使用类型注释。 Example: 例:
let inc (i, strs) = (i + 1, strs) in
inc (readOne ["1", "foo"])
-- (2, ["foo"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.