Re:Mostly Adequate Guide to Functional Programming in JavaSc...
by codygman on Tuesday July 14, 2015 @06:36PM
(#9888532)
> Hopefully some day it clicks.
While you wait for that, try writing useful code despite not fully understanding it.
Tell me what you think of the following code examples:
> sum . take 2 $ [1,2,3,4,5]
3
> -- now lets pretend we have a list of numbers we got from the DB
> let mockDBResponse = return [1,2,3,4,5] :: IO [Int]
> -- first lets try the exact same code as above
> sum . take 2 $ [1,2,3,4,5]
3
> sum . take 2 $ mockDBResponse
<interactive>:46:16:
Couldn't match expected type ‘[c]’ with actual type ‘IO [Int]’
Relevant bindings include it :: c (bound at <interactive>:46:1)
In the second argument of ‘($)’, namely ‘mockDBResponse’
In the expression: sum . take 2 $ mockDBResponse
> -- what to do? Use <$>
> import Control.Applicative ((<$>))
> sum . take 2 <$> mockDBResponse
3
1) Applying pure functions to pure functions sum . take 2 $ [1,2,3,4,5]
2) Applying pure functions to monadic functions that implement fmap of the Functor typeclass sum . take 2 <$> [1,2,3,4,5]
When I noticed that adding brackets around $ allowed me to apply pure functions to monadic ones a lot more made sense to me.
Re:Mostly Adequate Guide to Functional Programming in JavaSc...
by atrilumen on Tuesday July 14, 2015 @06:36PM
(#9888537)
Immutability is useful everywhere in the stack, even the database.
See "Turning the database inside out with Apache Samza" by Martin Kleppmann: https://www.youtube.com/watch?v=fU9hR3kiOK0
Most of us probably already follow best practices in terms of small functions, no global state, promises, composability etc. But at the end of every chain I have a db query and most of those mutate some data or other.
Hopefully some day it clicks.