美文网首页
初识函数式编程(三)

初识函数式编程(三)

作者: 拳战攻城师 | 来源:发表于2021-04-08 23:37 被阅读0次

容器、Functor(函子)

函子,遵守特殊规定的容器
标志,具有map方法

//平平无奇的容器
var Container = function(x){
  this.__value = x;
}
Container.of = x=> new Container(x);
Container.of('abcd');

//map方法,变形关系,把当前容器中的值可以变形到另一个容器
Container.prototype.map = function(f){
  return Container.of(f(this.__value));
}
//函子
Container.of(3)        //Container(3)
                .map(x=>x+1)  //Container(4)
                .map(x=>'Result is '+x);//Container('Result is 4');

map

class Functor{
    constructor(val){
        this.val = val;
    }
    map(f){
        return new Functor(f(this.val));
    }
};

//Functor(4)
(new Functor(2)).map(function(two){
    return two+2;
});

of

纯函数,用来生成新的容器

Functor.of = function(val){
    return new Functor(val);
}

maybe函子

class Maybe extends Functor{
    map(f){
        return this.val?Maybe.of(f(this.val)):Maybe.of(null);
    }
}
//Maybe(null)
Maybe.of(null).map(function(s){
    return s.toUpperCase();
})

Either

左值是右值不存在时的默认值
右值是正常情况下使用的值

class Either extends Functor{
    constructor(left,right){
        this.left = left;
        this.right = right;
    }

    map(f){
        return this.right?Either.of(this.left,f(this.right)):Either.of(f(this.left),this.right);
    }
}

Either.of = function(left,right){
    return new Either(left,right);
}

var addOne = funcion(x){
    return x+1;
}
Either.of(5,6).map(addOne);     //Either(5,7)
Either.of(1,null).map(addOne);  //Either(2,null)
// Either.of({address:'xxx'},currentUser.address).map(updateField);

Ap函子

class Ap extends Functor{
    ap(F){
        return Ap.of(this.val(F.val));
    }
}
//Functor(4)
Ap.of(addTwo).ap(Functor.of(2));

IO

负责处理脏数据

相关文章

  • 初识函数式编程(三)

    容器、Functor(函子) 函子,遵守特殊规定的容器标志,具有map方法 map of 纯函数,用来生成新的容器...

  • iOS-ReactiveCocoa使用之RACCommand

    前言 前几天开始研究Cocoa的第三方编程框架ReactiveCocoa,其使用响应式、函数式的编程思想,对于初识...

  • 函数式编程

    函数式编程初识 一.简介 他是和面向对象编程平起平坐的一种编程范式。 函数式编程就是一种抽象程度很高的编程范式,纯...

  • Swift函数式编程与面向协议编程

    函数式编程(FP) 一、函数式编程(FP)-高阶函数 二、函数式编程(FP) - 柯里化(Currying) 三、...

  • 初识函数式编程

    命令式编程 对于函数式编程,是早有耳闻,但是一直没有去了解过,正好最近有时间,就花一晚上了解了下。 要说函数式编程...

  • 函数式编程【1】——初识函数式编程

    1.一段话理解函数式编程 首先说一下函数和方法的区别,简单的可以理解为同一个东西,都是一个执行块。前者是面向过程的...

  • 函数式编程

    本文转载自: 函数式编程 当我们说起函数式编程来说,我们会看到如下函数式编程的长相: 函数式编程的三大特性:imm...

  • RxSwift初探(1)

    一、前提:函数响应式编程思想 简单来说 函数响应式编程 = 函数式编程 + 响应式编程 (1)函数式 函数式编程是...

  • iOS 函数编程 & 链式编程

    函数式(链式)编程 函数式编程概念 函数式编程是种编程范式 函数式编程 Functional Programmin...

  • Scala(三)-①-函数式编程和异常

    入门Scala(三)-① 函数式编程和异常 函数式编程 ① Why-为什么我们要学函数式编程.这种范式的目的 无目...

网友评论

      本文标题:初识函数式编程(三)

      本文链接:https://www.haomeiwen.com/subject/vdwlcltx.html