繁体   English   中英

Haskell:读取和输入签名

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM