[Javascript] IO Functor
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] IO Functor相关的知识,希望对你有一定的参考价值。
IO functor doesn‘t like Maybe(), Either() functors. Instead of get a value, it takes a function.
API:
.toIO() // conver a function to IO IO() // The same a to toIO; but this is a just static method runIO //IO is lazy, just like Observable, if you don‘t run it, it has no side effect
Examples:
/* Cover to IO */ var email_io = IO(function(){ return $("#email").val() } var getValue = function(sel){ return $(sel).val() }.toIO() /* Example runIO */ var email_io = IO(function(){ return $("#email").val() }) var msg_io = map(concat("welcome "), email_io) runIO(msg_io) //=> ”welcome [email protected]”
// Exercise 4 // ========== // Get the text from the input and strip the spaces console.log("--------Start exercise 4--------") var getValue = function(x){ return document.querySelector(x).value }.toIO() var stripSpaces = function(s){ return s.replace(/\s+/g, ‘‘); } var ex4 = compose(map(stripSpaces), getValue) assertEqual("honkeytonk", runIO(ex4(‘#text‘))) console.log("exercise 4...ok!") // Exercise 5 // ========== // Use getHref() / getProtocal() and runIO() to get the protocal of the page. var getHref = function(){ return location.href; }.toIO(); var getProtocal = compose(_.head, _.split(‘/‘)) var ex5 = compose(map(getProtocal), getHref) console.log("--------Start exercise 5--------") assertEqual(‘http:‘, runIO(ex5("http://www.google.fi"))) console.log("exercise 5...ok!") // Exercise 6* // ========== // Write a function that returns the Maybe(email) of the User from getCache(). // Don‘t forget to JSON.parse once it‘s pulled from the cache //so you can _.get() the email // setup... localStorage.user = JSON.stringify({email: "[email protected]"}) var log = function(x){ console.log(x.toString()); return x; } var getCache = function(x){ return Maybe(localStorage[x]); }.toIO(); var getEmail = compose(_.get(‘email‘), JSON.parse); var ex6 = compose(map(map(getEmail)), getCache); // one map for Maybe, one map for IO assertDeepEqual(Maybe("[email protected]"), runIO(ex6(‘user‘))) console.log("exercise 6...ok!")
以上是关于[Javascript] IO Functor的主要内容,如果未能解决你的问题,请参考以下文章
[Javascript] Functor Basic Intro
connect(QObject*, SIGNAL(signal()), functor) 未在 qt5 中连接
进阶学习4:函数式编程FP——函子FunctorMayBe函子Either函子IO函子FolktalePointer函子Monad