Created
January 27, 2017 08:28
-
-
Save simshanith/24af4ec9d9581997ad365ffb53908210 to your computer and use it in GitHub Desktop.
The Monad Fear: javascript response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://e.xtendo.org/monad#55 | |
['10', '10', '10'].map(parseInt); | |
//> [10, NaN, 2] | |
// parseInt('10', 0, [...]) === 10 // base 0 is falsey, thus default (?) guessing | |
// parseInt('10', 1, [...]) === NaN // base 1 does not compute | |
// parseInt('10', 2, [...]) === 2 // base 2 | |
// third parameter ignored; second parameter passed as index from map to functor | |
// higher-order functor to the rescue! | |
const onlyFirst = fun => single => fun(single); | |
['10', '10', '10'].map(onlyFirst(parseInt)); | |
//> [10, 10, 10] | |
// As a higher-order functor, `onlyFirst` takes and returns a functor, and is a functor itself | |
// While the index-as-base problem is solved, `parseInt` can demonstrate complex behavior | |
// Simple example of hexadecimal prefix `0x` | |
// `parseFloat` doesn't recognize; reads the first digit character up to the first non-digit character, thus interpreting the prefix as `0` | |
// By using the higher-order functor, compare/contrast comes easily | |
const withHexString = ['10', '10', '10', '0x10']; | |
[parseInt, parseFloat].map(onlyFirst).map(fn => withHexString.map(fn)); | |
//> [[10, 10, 10, 16], [10, 10, 10, 0]] | |
// Copy and paste gist contents into your console! (Chrome/Firefox macOS Sierra tested) |
@hartbeatnt - equally as valid, but not a higher order Functor, just a handy lambda. onlySingle
can work with functions other than parseInt
with minimal repetition. DRY vs abstraction overkill.
Honestly, I'd more likely write your solution than the generalized solution in practice, but as a response to Haskell programmers, it's nice to show off the FP capabilities of JS.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
['10', '10', '10'].map( (int)=>parseInt(int) ) ??