[Javascript] Other functor
EventStream:
You can use RxJS, BaconJS or any reactive programming lib you want:
var id_s = map(function(e) { return '#'+e.id }, Bacon.fromEventTarget(document, "click")) var element_s = map(document.querySelector, id_s) //=> EventStream(Element) element_s.onValue(function(el) { alert('The inner html is ' +el.innerHTML) })
Here using BaconJS; we need to call onValue to subscribe stream.
Future:
It is "lazy", you must fork it.
var makeHtml = function(post){ return "<div>"+post.title+"</div>"}; var page_f = map(makeHtml, http.get('/posts/2')) page_f.fork(function(err) { throw(err) }, function(page){ $('#container').html(page) })
console.clear(); var _ = R; var P = PointFree; var map = P.fmap; var compose = P.compose; var Maybe = P.Maybe; var Identity = P.Id; // Exercise 1 // ========== // Use _.add(x,y) and map(f,x) to make a function that increments a value inside a functor console.log("--------Start exercise 1--------") var ex1 = map(_.add(1)) assertDeepEqual(Identity(3), ex1(Identity(2))) console.log("exercise 1...ok!") // Exercise 2 // ========== // Use _.head to get the first element of the list var xs = Identity(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do']) console.log("--------Start exercise 2--------") var ex2 = map(_.head); assertDeepEqual(Identity('do'), ex2(xs)) console.log("exercise 2...ok!") // Exercise 3 // ========== // Use safeGet and _.head to find the first initial of the user var safeGet = _.curry(function(x,o){ return Maybe(o[x]) }) var user = {id: 2, name: "Albert"} console.log("--------Start exercise 3--------") var ex3 = compose(map(_.head), safeGet('name')); assertDeepEqual(Maybe('A'), ex3(user)) console.log("exercise 3...ok!") // Exercise 4 // ========== // Use Maybe to rewrite ex4 without an if statement console.log("--------Start exercise 4--------") var ex4 = function(n) { if(n){ return parseInt(n); } } var ex4 = compose(map(parseInt),Maybe) assertDeepEqual(Maybe(4), ex4("4")) console.log("exercise 4...ok!") // TEST HELPERS // ===================== function inspectIt(x){ return (x.inspect && x.inspect()) || (x.toString && x.toString()) || x.valueOf(); //hacky for teachy. } function assertEqual(x,y){ if(x !== y){ throw("expected "+x+" to equal "+y); } } function assertDeepEqual(x,y){ if(x.val !== y.val) throw("expected "+inspectIt(x)+" to equal "+inspectIt(y)); }
分类:
Javascript
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥