←back to thread

389 points kurinikku | 1 comments | | HN request time: 0.229s | source
Show context
marvinborner ◴[] No.42164919[source]
They give a nice introduction to encoding state as pure functions. In fact, there are many more purely functional encodings for all kinds of data like trees, integers, sum/product types, images, monads, ...

The encodings can be a bit confusing, but really elegant and tiny at the same time. Take for example a functional implementation of the Maybe monad in javascript:

  Nothing = nothing => just => nothing
  Just = v => nothing => just => just(v)
  
  pure = Just
  bind = mx => f => mx(mx)(f)
  
  evalMaybe = maybe => maybe("Nothing")(v => "Just " + v)
  console.log(evalMaybe(bind(Nothing)(n => pure(n + 1)))) // Nothing
  console.log(evalMaybe(bind(Just(42))(n => pure(n + 1)))) // Just 43
replies(5): >>42166462 #>>42166688 #>>42166841 #>>42168370 #>>42173549 #
solomonb ◴[] No.42166841[source]
You can derive these implementations from the recursion principle for your type:

  data Maybe a = Nothing | Just a

  foldMaybe :: (Unit -> r) -> (a -> r) -> Maybe a -> r
The two higher order functions passed into `foldMaybe` are your `Nothing` and `Just` (modulo I added the Unit param to the Nothing case to be a little more precise).
replies(1): >>42167071 #
1. gugagore ◴[] No.42167071[source]
If you have any light to shed, I'm wondering about inductive data types and their expressive necessity here: https://news.ycombinator.com/item?id=42166709