【问题标题】:Return a value from a list of type synonyms从类型同义词列表中返回一个值
【发布时间】:2015-12-13 04:07:18
【问题描述】:

所以我想从类型同义词列表中返回一个值。

type Skill = (String,Int)
type Stat = (String,Int)
data Player = Player {
                   hitpoints :: Int,
                   experience :: Int,
                   stats :: [Stat],
                   skills :: [Skill],
                   pos :: Point
                   }

我想在

中返回stat "Toughness"的值

Player 10 0 [ ("Strength", 5), ("Toughness", 1) ] [ ("Fisticuffs", 1) ] (1,1)

到现在为止

instance Combatant Player where
defense (Player _ _ ([(s,a)]) _ _) = (List.find (s=="Toughness") ([(s,a)]))

但它返回以下错误

Couldn't match expected type `Int'
            with actual type `Maybe (GHC.Base.String, Int)'
In the expression: (find (s == "Toughness") ([(s, a)]))
In an equation for `defense':
    defense (Player _ _ ([(s, a)]) _ _)
      = (find (s == "Toughness") ([(s, a)]))


Couldn't match expected type `(GHC.Base.String, Int)
                              -> ghc-prim-0.4.0.0:GHC.Types.Bool'
            with actual type `ghc-prim-0.4.0.0:GHC.Types.Bool'
In the first argument of `find', namely `(s == "Toughness")'
In the expression: (find (s == "Toughness") ([(s, a)]))
In an equation for `defense':
    defense (Player _ _ ([(s, a)]) _ _)
      = (find (s == "Toughness") ([(s, a)]))

我还是 Haskell 的新手,我不知道我应该做什么。我查看了不同的来源并关闭了我所看到的关联列表?

【问题讨论】:

    标签: haskell type-synonyms


    【解决方案1】:

    类型同义词与您的问题无关。函数式编程的一大优点是它允许您抽象出越来越多的方法来组合结果。所以所有常见的问题都已经解决了,你只需要找到解决方案的名称。看看Data.List,它有lookup功能:

    λ> lookup "Toughness" [("Strength", 5), ("Toughness", 1)]
    Just 1
    

    您会发现,您目前在类型级别上无法保证您会找到标记为"Toughness" 的东西。因此我们得到Maybe Int。现在你应该问自己一个问题,玩家可以在没有"Toughness"参数的情况下存在吗?可能不是。所以更好的方法是:

    data Player = Player
      { hitpoints       :: Int
      , experience      :: Int
      , statStrength    :: Int
      , statToughness   :: Int
      , skillFisticuffs :: Maybe Int
      , pos             :: Point }
    

    这好多了,你现在保证任何玩家都会有一些力量等等。我不知道你的游戏中的技能,你可以将它们设为可选Maybe 包装器或将它们保存在具有相同效果的映射(元组列表)中(参见lookup,它也返回Maybe Int)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-21
      • 2015-02-18
      相关资源
      最近更新 更多