4 ms·
Something that might be worth pointing out to folks newer to haskell is this syntax location.x `over` (+10) $ player1 Here, `over` is not a string. This i
by IanCal 13y ago
Something that might be worth pointing out to folks newer to haskell is this syntax
location.x `over` (+10) $ player1
Here, `over` is not a string. This is not stringly typed programming. It translates to
over (location.x) (+ 10) $ player1
It's used to take a function that would normally be
function_name argument1 argument2
and allow you to call it like so
argument1 `function_name` argument2
so
plus 1 2 = 1 `plus` 2
There's nothing special you need to do, and it's purely a style thing. Sometimes it's easier to read.
Edit - fix from DanWaterworth, the . in location.x is (if I understand the problem correctly) function composition and therefore location.x is location . x, so my re-ordering possibly changed things more than I thought. The principle is the same, but I've wrapped location.x in parentheses, just to be sure. I'm sure someone more well versed in haskell can correct me on this :)
- ozataman 13y agoFor example: I personally prefer the standard form here, as (to me) it reads a bit more like English: over (location.x) (+ 10) $ player1 "over location's x, add 10"
- tel 13y agoThere's also the player1 & location.x .~ (+10) format which has a nice scansion.
- drostie 13y agoIt seems like there should be a way to define player1 as its own (root) lens so that one is simply writing player1.location.x .~ (+10), or so. Are we simply not doing this because it makes reading the data structure rather difficult?
- tel 13y agoThat can kind of be done using `Context`s, but those are really just implementation details and should rarely be used. Broadly, you wouldn't want to do that because it implies mutation. There's not much value in `player1.location.x %~ (+10)` because it can't modify player1... just return a modified (player1'new). Of course, stateful mutation is just a monadic effect, so you can wrap it up into a State monad, which Lens already has shortcuts for do location.x += 10 location.y += 10 which has type like `MonadState ThingWithLocation m => m ()` and we can then apply it to whatever `player` we want as a pure function.
- DanWaterworth 13y agoI haven't checked this, but I believe that: over location.x (+ 10) $ player1 Would be read as: (over location) . (x (+ 10)) $ player1 It looks like what you want is: over (location . x) (+ 10) $ player1