3 ms·
> 2. Use StateT and lenses. Your code can even look almost exactly like C if you want, with for and while loops with the same semantics as in C. I often use thi
by surement 9y ago
> 2. Use StateT and lenses. Your code can even look almost exactly like C if you want, with for and while loops with the same semantics as in C. I often use this when implementing heavily imperative papers in Haskell. It's still pure and everything, but looks just like an imperative language and performs well (if maybe not always full C speed).
I am no Haskell expert and that sounds quite interesting. Do you have any links to examples?
- wyager 9y agoShoot, I had some great example code from a few years ago but it was part of a uni assignment so the university made us take it off github. Here's a fairly in-depth analysis of the approach: http://www.haskellforall.com/2013/05/program-imperatively-using-haskell.html?m=1 http://www.haskellforall.com/2013/05/program-imperatively-us... The gist of it is that StateT gives you nice syntactic sugar around state-update functions of type `state -> (state, result)`. Let's say your state type is like data Boss = Boss { health :: Int, ... } data Player = ... data State = State { boss :: Boss, player :: Player, ... } Using Lenses, you can construct StateT operations like this: boss.health -= 1 player.stats.score += 5 Where each of those updates the state as you imagine. So your code just looks like a bunch of stateful OO-style updates, but it's actually pure. This also lets you do a bunch of cool stuff that you can't do with real imperative code in this fashion, like re-interpret the semantics of assignment or modification, but that's for another time.