[Haskell-beginners] Using Traversal as a kind of pointer
Daniel Trstenjak
daniel.trstenjak at gmail.com
Mon Aug 18 14:03:22 UTC 2014
Hi Elise,
> thanks for your answer. That looks like something that might work -
> however, having never worked with Optics, I'm not entirely sure
> whether I'm doing it right, getting an error:
oh sorry, there has to be a 'traversed' before the 'filtered'.
> Also, may I ask what the '&' is in your proposed solution?
The '&' is just applying a lens to a variable.
So here's a working example:
{-# LANGUAGE Rank2Types #-}
import Control.Lens
type Background = Int
type Lifeform = Int
type Player = Int
data World = World Background [Lifeform] deriving (Show)
lifeforms :: Lens' World [Lifeform]
lifeforms = lens getLifeforms setLifeforms
where
getLifeforms (World _ lifeforms) = lifeforms
setLifeforms (World bg _) lifeforms = World bg lifeforms
colliding :: Player -> Traversal' [Lifeform] Lifeform
colliding player = traversed . filtered (== player)
If you load this into ghci und can write:
> World 1 [1, 2] & lifeforms . colliding 1 %~ (+ 10)
> World 1 [11,2]
Greetings,
Daniel
More information about the Beginners
mailing list