gpt4 book ai didi

haskell - RankNTypes 和范围 `forall'

转载 作者:行者123 更新时间:2023-12-03 21:27:12 30 4
gpt4 key购买 nike

这些有什么区别?

{-# LANGUAGE RankNTypes #-}

f :: forall a. a -> Int
f _ = 1

g :: (forall a. a) -> Int
g _ = 1

特别是,为什么我会收到 g () 的错误? ?
ghci> f ()
1
ghci> g ()
<interactive>:133:3:
Couldn't match expected type `a' with actual type `()'
`a' is a rigid type variable bound by
a type expected by the context: a at <interactive>:133:1
In the first argument of `g', namely `()'
In the expression: g ()
In an equation for `it': it = g ()

ghci> f undefined
1
ghci> g undefined
1

最佳答案

f只是一个普通的多态 Haskell98 函数,除了 forall是明确写出来的。所以签名中的所有类型变量都是调用者可以选择的参数(没有任何约束);在您的情况下,它已解决 a ~ () .
g OTOH 具有 2 级类型。它要求其参数具有多态类型 forall a . a . ()没有这种类型,它是单态的。但是undefined有这种类型(其实只有undefined和error等),如果我们添加显式forall再次。

也许使用不那么简单的 Rank2 函数会变得更清楚:

h :: (forall a . (Show a, Num a) => a) -> String
h a = show a1 ++ " :: Double\n"
++ show a2 ++ " :: Int"
where a1 :: Double; a2 :: Int
a1 = a; a2 = a

GHCi> putStrLn $ h 4
4.0 :: Double
4 :: Int



但我做不到

GHCi> putStrLn $ h (4 :: Integer)

<‌interactive>:4:15:
    Could not deduce (a ~ Integer)
    from the context (Show a, Num a)
      bound by a type expected by the context: (Show a, Num a) => a
      at <‌interactive>:4:12-27
      `a' is a rigid type variable bound by
          a type expected by the context: (Show a, Num a) => a
          at <‌interactive>:4:12
    In the first argument of `h', namely `(4 :: Integer)'
    In the second argument of `($)', namely `h (4 :: Integer)'
    In the expression: putStrLn $ h (4 :: Integer)

关于haskell - RankNTypes 和范围 `forall',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20401018/

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