gpt4 book ai didi

haskell - 理解 readMaybe (Text.Read)

转载 作者:行者123 更新时间:2023-12-05 00:13:24 26 4
gpt4 key购买 nike

我正在学习 Haskell 并且对在 Joachim Breitner's online course CIS194 中找到的这个例子有疑问。 :

import Text.Read
main = putStrLn "Hello World. Please enter a number:" >>
getLine >>= \s ->
case readMaybe s of -- why not `readMaybe s :: Maybe Int` ?!
Just n -> let m = n + 1 in
putStrLn (show m)
Nothing -> putStrLn "That’s not a number! Try again"

代码完全符合预期,即如果输入是整数,则返回整数 +1,否则返回“这不是数字!再试一次”(例如,如果输入是 Double)。
我不明白为什么 readMaybe s只返回 Just n如果 n类型为 Int . readMaybe的类型是 readMaybe :: Read a => String -> Maybe a因此我认为它只有在该行改为:
case readMaybe s :: Maybe Int of

其实如果我只是提示 > readMaybe "3"在 ghci 中,它返回 Nothing , 而 > readMaybe "3" :: Maybe Int返回 Just 3 .

综上所述,我的问题如下:现在编译器如何 s被解析为 Int不使用 Double 而不是其他东西(例如 :: Maybe Int ) ?为什么不返回 Nothing每次 ?

我希望我的问题足够清楚,非常感谢您的帮助。

最佳答案

TL;博士: readMaybe s的上下文告诉我们这是一个 Num a => Maybe a , 默认使它成为 Maybe Integer .

我们要查看readMaybe结果所在的所有地方用于确定其类型。
我们有

  • Nothing ,这并没有告诉我们有关 a 的任何信息
  • Just n , 和 n用于上下文 m = n + 1 .

  • m = n + 1 ,我们现在知道 n的类型必须是 Num 的实例, 自 (+) :: Num a => a -> a -> a1 :: Num a => a .此时类型不清楚,因此 gets default ed :

    4.3.4 Ambiguous Types, and Defaults for Overloaded Numeric Operations

    topdecl   ->  default (type1 , ... , typen)   (n>=0)

    A problem inherent with Haskell -style overloading is the possibility of an ambiguous type. For example, using the read and show functions defined in Chapter 10, and supposing that just Int and Bool are members of Read and Show, then the expression

    let x = read "..." in show x -- invalid

    is ambiguous, because the types for show and read,

    show  :: forall a. Show a =>a ->String
    read :: forall a. Read a =>String ->a

    could be satisfied by instantiating a as either Int in both cases, or Bool. Such expressions are considered ill-typed, a static error.

    We say that an expression e has an ambiguous type if, in its type forall u. cx =>t, there is a type variable u in u that occurs in cx but not in t. Such types are invalid.

    default Haskell 报告中定义的 s 是 default (Integer, Double) ,例如GHC 尝试 Integer首先,如果这不起作用,它会尝试使用 Double .
    Integer是上下文中的有效类型 m = n + 1 , 我们有 m :: Integer ,因此 n :: Integer ,最后 readMaybe s :: Maybe Integer .
    如果您想禁用 default s,使用 default ()正如您所料,您会遇到模棱两可的类型错误。

    关于haskell - 理解 readMaybe (Text.Read),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48663946/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com