The Monad Maybe
Maybe aka option or optional is very useful for preventing null. Using the Javascript library Monet it's quite easy to use this monad.
Preventing null
You have a variable but don't know if it's null. With Maybe, you wrap it and test if it is "some".
This file contains hidden or 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
var couldBeNull = Maybe.fromNull(suspiciousVariable); | |
if (couldBeNull.isSome()) { | |
// Ok | |
} else { | |
// KO! | |
} |
Transform or map
Monads are also useful to transform a value to another. Think of this example:
This file contains hidden or 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
var text = "10"; | |
var integer = parseInt(text); | |
var array = new Array(integer); | |
for (var i=0; i<integer; i++) { | |
array[i] = i; | |
} | |
console.log(array); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Each step is instancing a variable and making a "halt". With a monad, you can "go with the flow" and do it all in one step:
This file contains hidden or 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
console.log( | |
Some("10").map(function(text) { | |
return parseInt(text); | |
}).map(function(integer) { | |
return new Array(integer); | |
}).map(function(array) { | |
for (var i=0; i<array.length; i++) { | |
array[i] = i; | |
} | |
return array; | |
}).some(); | |
); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Inga kommentarer:
Skicka en kommentar