无法将类型“*”与 'Nat' 匹配
Couldn't match kind '*' with 'Nat'
我正在尝试创建一种保证字符串长度小于 N 个字符的类型。
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DataKinds #-}
import GHC.TypeLits (Symbol, Nat, KnownNat, natVal, KnownSymbol, symbolVal)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Proxy (Proxy(..))
data TextMax (n :: Nat) = TextMax Text
deriving (Show)
textMax :: KnownNat n => Text -> Maybe (TextMax n)
textMax t
| Text.length t <= (fromIntegral $ natVal (Proxy :: Proxy n)) = Just (TextMax t)
| otherwise = Nothing
这给出了错误:
src/Simple/Reporting/Metro2/TextMax.hs:18:50: error:
• Couldn't match kind ‘*’ with ‘Nat’
When matching the kind of ‘Proxy’
• In the first argument of ‘natVal’, namely ‘(Proxy :: Proxy n)’
In the second argument of ‘($)’, namely ‘natVal (Proxy :: Proxy n)’
In the second argument of ‘(<=)’, namely
‘(fromIntegral $ natVal (Proxy :: Proxy n))’
我不明白这个错误。为什么它不起作用? 。
有更好的方法吗?
您需要在 textMax
的签名中显式 forall
,这样 ScopedTypeVariables
就会生效,并且 Proxy n
注释中的 n
成为KnownNat n
约束中的相同 n
:
textMax :: forall n. KnownNat n => Text -> Maybe (TextMax n)
textMax t
| Text.length t <= (fromIntegral $ natVal (Proxy :: Proxy n)) = Just (TextMax t)
| otherwise = Nothing
我正在尝试创建一种保证字符串长度小于 N 个字符的类型。
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DataKinds #-}
import GHC.TypeLits (Symbol, Nat, KnownNat, natVal, KnownSymbol, symbolVal)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Proxy (Proxy(..))
data TextMax (n :: Nat) = TextMax Text
deriving (Show)
textMax :: KnownNat n => Text -> Maybe (TextMax n)
textMax t
| Text.length t <= (fromIntegral $ natVal (Proxy :: Proxy n)) = Just (TextMax t)
| otherwise = Nothing
这给出了错误:
src/Simple/Reporting/Metro2/TextMax.hs:18:50: error:
• Couldn't match kind ‘*’ with ‘Nat’
When matching the kind of ‘Proxy’
• In the first argument of ‘natVal’, namely ‘(Proxy :: Proxy n)’
In the second argument of ‘($)’, namely ‘natVal (Proxy :: Proxy n)’
In the second argument of ‘(<=)’, namely
‘(fromIntegral $ natVal (Proxy :: Proxy n))’
我不明白这个错误。为什么它不起作用?
有更好的方法吗?
您需要在 textMax
的签名中显式 forall
,这样 ScopedTypeVariables
就会生效,并且 Proxy n
注释中的 n
成为KnownNat n
约束中的相同 n
:
textMax :: forall n. KnownNat n => Text -> Maybe (TextMax n)
textMax t
| Text.length t <= (fromIntegral $ natVal (Proxy :: Proxy n)) = Just (TextMax t)
| otherwise = Nothing