【问题标题】:Sum type with HashMap使用 HashMap 的 Sum 类型
【发布时间】:2021-04-29 15:01:27
【问题描述】:

以下代码触发错误:

import           Data.HashMap.Strict (HashMap) -- from unordered-containers
import           Data.Text

data Value =
    VText Text
  | VList [Text]
  | VMap HashMap Text Text
  deriving Show

编译器抱怨:

Expecting two more arguments to ‘HashMap’
  Expected a type, but ‘HashMap’ has kind ‘* -> * -> *’
  In the type ‘HashMap’
  In the definition of data constructor ‘VMap’
  In the data declaration for ‘Value’typecheck

如何创建像 Value 这样的总和类型,其中一个构造函数采用 HashMap Text Text

【问题讨论】:

    标签: haskell hashmap algebraic-data-types sum-type


    【解决方案1】:

    通过使用括号消除HashMapVMap 中的参数的歧义:

    data Value =
        VText Text
      | VList [Text]
      | VMap (HashMap Text Text)
      deriving Show
    

    【讨论】:

    • 我的印象是我尝试了所有可能的括号组合,除了这个特殊的组合......非常感谢
    • @Jivan:如果您发现传统的data 语法令人困惑,另一种选择是{-# Language GADTSyntax #-},您可以在其中显式编写每个构造函数的类型:data Value where { VText :: Text -> Value; VList :: [Text] -> Value; VMap :: HashMap Text Text -> Value; }。您在原始帖子中的内容相当于说VMap :: HashMap -> Text -> Text -> Value;如果您尝试使用 HashMap(Text, Text)HashMap (Text Text) 之类的括号,它们分别表示 HashMap -> (Text, Text) -> ValueHashMap -> Text Text -> Value — 我希望能澄清为什么它们不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2021-07-08
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多