4 ms·
Pure functional programming means that everything a function does has to be part of the return type. That means you often get functions like a -> Maybe b
by Tarean 10y ago
Pure functional programming means that everything a function does has to be part of the return type. That means you often get functions like
a -> Maybe b
Instead of throwing an exception or returning null to make the possible failure part of the return type. Chaining failable functions would be incredibly annoying, though:
let a = tryRead
if isNothing a
then Nothing
else
let b = tryParse (unwrap a)
if isNothing b...
In imperative code you could flatten this with early returns but that still is a common pattern, so lets abstract this!
tryRead >>= tryParse >>= tryProcess
The magic sauce is in the >>= combinator, pronounced bind or andThen. It returns Nothing instantly if it receives Nothing, otherwise it unwraps it and calls the next function.
There are a lot of other things that we could encode in a generic type tacked onto the return value and which we want to chain like this.
Futures in async io, passing around config/state instead of having global variables or the order in which ffi/io is run (the use case you have heard of most) would be a couple examples. You can even abuse bind to add things like implicit backtracking on failure!
So the really cool thing about monads is that you can add new behavior to functions without implementation details leaking during composition!
The cool thing about lenses is that they enable getters/setters for things like entries in a hashmap or all string fields in a struct at once.
- nickpsecurity 10y ago"So the really cool thing about monads is that you can add new behavior to functions without implementation details leaking during composition! The cool thing about lenses is that they enable getters/setters for things like entries in a hashmap or all string fields in a struct at once." Good reply. Yeah, I definitely see these as beneficial.