无法将'*'与'Nat'匹配

时间:2016-11-21 23:19:32

标签: haskell types data-kinds

我正在尝试创建一个类型,以确保字符串长度小于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))’

我不明白这个错误。为什么不起作用? I've used almost this exact same code to get the natVal of n in other places and it works

有更好的方法吗?

1 个答案:

答案 0 :(得分:8)

您需要在forall的签名中使用明确的textMax,以便ScopedTypeVariables启动并n注释中的Proxy n变为相同{ {1}}约束中的{1}}:

n