我目前正在学习镜头库,通过使用这个库编写一些简单的函数。不幸的是,我被生成的编译器错误搞糊涂了,所以我很难确定为什么在下面的函数dmg中前两个函数编译正确,但是最后一个函数失败了。
import Control.Lens
type Health = Int
type Damage = Int
data Card = Card {
_health :: Int,
_damage :: Int
} deriving (Show,Eq)
health :: Lens' Card Health
health = lens _health (\card h -> card { _health = h })
damage :: Lens' Card Damage
damage = lens _damage (\card d -> card { _damage = d })
cardDead :: Card -> Bool
cardDead c = c^.health <= 0
duel :: (Card,Card) -> (Card,Card)
duel (c,c2) = ((dmg c c2),(dmg c2 c))这件事的真谛。
dmg :: Card -> Card -> Card
dmg myCard otherCard = over health ((-) (otherCard^.damage)) myCard --compiles
dmg myCard otherCard = myCard & health %~ ((-) (otherCard^.damage)) --compiles
dmg myCard otherCard = health %~ ((-) (otherCard^.damage)) myCard --compile error我的问题分为三部分。
(%~)操作符,而不是使用(&),并且仍然编译?dmg?--
作为参考,这里有一种不用镜头就可以写dmg的方法。
dmg myCard otherCard =
let
damageTaken = _damage otherCard
oldHealth = _health myCard
newHealth = oldHealth - damageTaken
in myCard {_health = newHealth}编辑:作为参考,这是我在理解(写错了)第3行时遇到的错误信息。
*Main GHC.Arr Control.Applicative Control.Lens> :l Doom.hs
[1 of 1] Compiling Main ( Doom.hs, interpreted )
Doom.hs:26:24:
Couldn't match expected type `Card' with actual type `Card -> Card'
In the expression: health %~ ((-) (otherCard ^. damage)) myCard
In an equation for `dmg':
dmg myCard otherCard = health %~ ((-) (otherCard ^. damage)) myCard
Doom.hs:26:51:
Couldn't match type `Health -> Health' with `Int'
Expected type: Getting (Health -> Health) Card (Health -> Health)
Actual type: (Damage -> Const (Health -> Health) Damage)
-> Card -> Const (Health -> Health) Card
In the second argument of `(^.)', namely `damage'
In the first argument of `(-)', namely `(otherCard ^. damage)'
Doom.hs:26:60:
Couldn't match expected type `Health -> Health'
with actual type `Card'
In the second argument of `(-)', namely `myCard'
In the second argument of `(%~)', namely
`((-) (otherCard ^. damage)) myCard'
Failed, modules loaded: none.
Prelude GHC.Arr Control.Applicative Control.Lens>发布于 2017-06-02 12:38:26
def %~ ghi(jkl)。(def %~ ghi) jkl。这通常是在Haskell中用$实现的,即
dmg myCard otherCard = health %(-)(otherCard^.damage)$ myCard^.比-绑定得更紧,
dmg myCard otherCard = health %~ (otherCard^.damage -) $ myCard
接下来,我将尝试减少η。如果交换参数,这将很容易,这可能是Haskell-惯用的参数顺序:
dmg otherCard myCard = health %~ (otherCard^.damage -) $ myCard dmg otherCard = health %~ (otherCard^.damage -)
这可能是最优雅的解决方案。也就是说,假设您的代码实际上是正确的。我不知道dmg应该做什么,但是也许更常见的情况是你想从你的卡中减去另一张卡的伤害。也就是说,基本上不是(otherCard^.damage -),而是(- otherCard^.damage),但它被解析为一元减号,因此需要编写subtract (otherCard^.damage)。镜头有专门的加减符,给你
dmg otherCard = health -~ otherCard^.damagehttps://stackoverflow.com/questions/44327686
复制相似问题