Part2-applicative


  • 0
    administrators

    根据代码注释编写相应的函数。代码引入了一个支持性质的依赖文件 support.js,源码可见 github,还有已经引入了 Ramda.js 和 data.task.js。

    参考答案在讨论区。


  • 0
    administrators

    参考答案:

    var _ = R;
    
    // fib browser for test
    var localStorage = {};
    
    
    
    // Exercise 1
    // ==========
    // Write a function that add's two possibly null numbers together using Maybe and ap()
    
    var ex1 = function(x, y) {
      return Maybe.of(_.add).ap(Maybe.of(x)).ap(Maybe.of(y));
    };
    
    
    // Exercise 2
    // ==========
    // Rewrite 1 to use liftA2 instead of ap()
    
    var ex2 = liftA2(_.add);
    
    
    
    // Exercise 3
    // ==========
    // Run both getPost(n) and getComments(n) then render the page with both. (the n arg is arbitrary)
    var makeComments = _.reduce(function(acc, c){ return acc+"<li>"+c+"</li>" }, "");
    var render = _.curry(function(p, cs) { return "<div>"+p.title+"</div>"+makeComments(cs); });
    
    
    var ex3 = Task.of(render).ap(getPost(2)).ap(getComments(2));
    // or
    // var ex3 = liftA2(render, getPost(2), getComments(2))
    
    
    
    
    // Exercise 4
    // ==========
    // Write an IO that gets both player1 and player2 from the cache and starts the game
    localStorage.player1 = "toby";
    localStorage.player2 = "sally";
    
    var getCache = function(x) {
      return new IO(function() { return localStorage[x]; });
    }
    var game = _.curry(function(p1, p2) { return p1 + ' vs ' + p2; });
    
    var ex4 = liftA2(game, getCache('player1'), getCache('player2'));
    
    
    
    
    
    // TEST HELPERS
    // =====================
    
    function getPost(i) {
      return new Task(function (rej, res) {
        setTimeout(function () { res({ id: i, title: 'Love them tasks' }); }, 100);
      });
    }
    
    function getComments(i) {
      return new Task(function (rej, res) {
        setTimeout(function () {
          res(["This book should be illegal", "Monads are like space burritos"]);
        }, 100);
      });
    }
    

登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待