Skip to content

Instantly share code, notes, and snippets.

@asktree
Last active March 1, 2021 22:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asktree/18cdfbed89773a5a09f9aa259cc3d274 to your computer and use it in GitHub Desktop.
Save asktree/18cdfbed89773a5a09f9aa259cc3d274 to your computer and use it in GitHub Desktop.
Confusion-aware explanation of monadic mapping that I am proud of
" Summary: "
`
I recently had an aha! moment. I finally understood what mapping functions are in Functional Programming,
*and* I finally understood why JS had made learning the FP meaning confusing.
`
` this makes it obvious "map" means in Functional Programming`
A.map(add1)(myArray)
` this makes it confusing: `
myArray.map(add1)
" # Part 1: Monads and mapping "
// -----
`
Let's say I'm a mapping function. What does that mean?
Firstly it means I'm a higher-order function (a function that inputs a function and outputs another function).
Basically I take a function of type:
'a => 'b
and make it a function of type:
'M<'a> => 'M<'b>
Why mention monads? Well, if 'M is a monad, then I'm defined.
`
// by the way, the tick notation ' is just how ML languages denote anonymous types. Anonymous types are an awesome feature that I wish TS had, but I digress.
`
so let's imagine a function "A.map" that takes a function of type:
'a => 'b
and makes it a function of type:
Array<'a> => Array<'b>
`
// fp-ts provides this function!
import * as A from 'fp-ts/Array'
const myArray = [1,2,3]
const add1 = x => x+1
console.log (A.map(add1)(myArray))
" # Part 2: Confusion "
// -----
// So I wanted to give this context ^ before I explained my confusion, lest I confuse you too!
`
With JS Arrays, the ".map" we know and love is a method, not a higher-order function.
`
console.log (myArray.map(add1))
` So you end up with this generation of programmers who know "map" divorced from its original(?) monadic context.
People (including me) say stuff like "mapping over an array". "Just take add1 and map it over myArray"
But that makes it confusing when you talk about "map" in the monadic context!
I wish they'd have called it myArray.transform instead.
`
// Extra credit: what *does* Array.prototype.map have in common with a mapping function?
" # Part 3: Exercise for the reader "
console.log(Promise.map === undefined)
` write this higher-order function: `
// Promise.map =
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment