所以我想从类型同义词列表中返回一个值。
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的新手,我不知道该怎么办。我看过不同的消息来源并关闭了我看到过的关联列表?
答案 0 :(得分:2)
类型同义词与您的问题无关。函数式编程的一个好处是它允许您抽象越来越多的方法来组合结果。因此,所有常见问题都已解决,您只需要找到解决方案的名称。看看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
)。