[Haskell-beginners] Using Traversal as a kind of pointer
Elise Huard
haskell at elisehuard.be
Tue Aug 19 08:37:48 UTC 2014
Thanks for the example! I found another example of filtered here
http://www.haskellforall.com/2013/05/program-imperatively-using-haskell.html
I'm aware that filtered traversals should only ever be used with
functions that will not change the number of elements filtered.
Thank you!
Elise
On 18 August 2014 16:03, Daniel Trstenjak <daniel.trstenjak at gmail.com> wrote:
>
> 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
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
More information about the Beginners
mailing list