函数式编程

2020-05-26  本文已影响0人  酸菜牛肉

作者:酸菜牛肉 文章内容输出来源:拉勾教育大前端高薪训练营课程

函数式编程概念:

函数式编程是一种编程范式;还有面向对象编程,和面向过程编程

  1. 程序的本质: 根据输入通过某种运算获得相应输出,程序开发过程中会涉及很多有输入和输出的函数
  2. x -> f(联系、映射)-> y, y=f(x)
  3. 函数式编程中的函数指的不是程序中的函数(方法),而是数学中的函数即映射关系,例如:y = sin(x), x和y的关系
  4. 相同的输入始终要得到相同的输出(纯函数)
  5. 函数式编程用来描述数据(函数)之间的映射
前置知识:
函数是一等公民
//把函数赋值给变量
let fn = function() {
  console.log('hello world')
}
fn()

const BlogController = {
  index(posts){return Views.index(posts) } // 函数的调用相同,可以将后边函数本身赋值给变量,(而不是函数的调用)
}
// 优化
const BlogController = {
  index: Views.index
}
高阶函数
//函数作为参数
const filter = (array, fn) => {
  let results = []
  for(let i =0; i< array.length; i++){
    if(fn(array[i]){
      results.push(array[i])
    }
  }
  return results
}
let arr = [1, 3, 4, 7, 8]
const a = filter(arr, (item)=>{
   return item % 2 === 0
})

//函数作为函数返回值 
const makeFn = () => {
  let msg = 'hello function'
  return function(){
   console.log(msg);  
 }
}
makeFn()()
//once
const once = (fn) => {
  let done  = false
  return function(){
    if(!done){
      done = true
      return fn.apply(this, arguments)
    }
  }
}

let pay = once(function(money)=>{
  consle.log(`支付:${money}RMB`)
})
pay(5)
pay(5)
pay(5)
pay(5)
使用高阶函数的意义
常用高阶函数
const map = (array, fn) => {
    let result = []
    for (let value of array) {
        result.push(fn(value))
    }
    return result
 } 
const every = (array, fn) => {
    let result = true
    for (let value of array) {
        result = fn(value)
        if(!result){
            break
        }
    }
    return result
}

const some = (array, fn) => {
    let result = false
    for (let value of array) {
        result = fn(value)
        if(result){
            break
        }
    }
    return result
}


let arr = [1, 2, 3, 4]
// arr = map(arr, v => v * v)
// a = every(arr, v => v > 0)
b = some(arr, v => v > 3)
console.log(b)
闭包

闭包: 函数和其周围的状态(词法环境)的引用捆绑在一起形成闭包
可以在另一个作用域中调用一个函数的内部函数并访问到该函数的作用域中的成员

//闭包;
//once

function once (fn) {
    let done = false   //此变量的作用范围被延长,用来标记此函数是否被执行
    return function () {
        if(!done){
            done = true
            return fn.apply(this, arguments)
        }
    }
}

let pay = once(function(money){
    console.log(`支付: ${money} RMB`)
})

pay(5)
// pay(5)
// pay(5)

闭包的本质:函数在执行的时候会放在一个执行栈上,当函数执行完毕之后会从执行栈上移除,但是堆上的作用域成员因为被外部引用不能被释放,因此内部函数依然可以访问外部函数的成员。

纯函数

纯函数的定义是:

lodash

lodash 官网

纯函数的好处
// 记忆函数
const _ = require('lodash')

function getArea (r) {
  console.log(r)
  return Math.PI * r * r
}

// let getAreaWithMemory = _.memoize(getArea)
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))
// console.log(getAreaWithMemory(4))

// 模拟 memoize 方法的实现

function memoize (f) {
  let cache = {}
  return function () {
    let key = JSON.stringify(arguments)
    cache[key] = cache[key] || f.apply(f, arguments)
    return cache[key]
  }
}

let getAreaWithMemory = memoize(getArea)
console.log(getAreaWithMemory(4))
console.log(getAreaWithMemory(4))
console.log(getAreaWithMemory(4))
纯函数副作用

如果函数依赖于外部的状态就无法保证输出相同,就会带来副作用。
副作用来源:

柯里化 <Currying>
// 函数的柯里化
// function checkAge (min) {
//   return function (age) {
//     return age >= min
//   }
// }

// ES6
let checkAge = min => (age => age >= min)

let checkAge18 = checkAge(18)
let checkAge20 = checkAge(20)

console.log(checkAge18(20))
console.log(checkAge18(24))

lodash 中柯里化
_.curry(func)

const _ = require('lodash')

const getSum = (a, b, c) => a + b + c

const curried = _.curry(getSum)

console.log(curried(1, 2, 4))
console.log(curried(1, 4)(4))
console.log(curried(14)(4)(3))
// 模拟实现 lodash 中的 curry 方法

function getSum (a, b, c) {
  return a + b + c
}

const curried = curry(getSum)

console.log(curried(1, 2, 3))
console.log(curried(1)(2, 3))
console.log(curried(1, 2)(3))


function curry (func) {
  return function curriedFn(...args) {
    // 判断实参和形参的个数
    if (args.length < func.length) {
      return function () {
        return curriedFn(...args.concat(Array.from(arguments)))
      }
    }
    return func(...args)
  }
}
柯里化总结
函数组合
// 函数组合演示
function compose (f, g) {
  return function (value) {
    return f(g(value))         
  }
}

function reverse (array) {
  return array.reverse()
}

function first (array) {
  return array[0]
}

const last = compose(first, reverse)

console.log(last([1, 2, 3, 4]))
lodash中的组合函数
// lodash 中的函数组合的方法 _.flowRight()
const _ = require('lodash')

const reverse = arr => arr.reverse()
const first = arr => arr[0]
const toUpper = s => s.toUpperCase()

const f = _.flowRight(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))

// 模拟 lodash 中的 flowRight
// function compose (...args) {
//   return function (value) {
//     return args.reverse().reduce(function (acc, fn) {
//       return fn(acc)
//     }, value)
//   }
// }

const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)

const f = compose(toUpper, first, reverse)
console.log(f(['one', 'two', 'three']))

函数的组合满足结合律:

// 函数组合要满足结合律
const _ = require('lodash')

// const f = _.flowRight(_.toUpper, _.first, _.reverse)
// const f = _.flowRight(_.flowRight(_.toUpper, _.first), _.reverse)
const f = _.flowRight(_.toUpper, _.flowRight(_.first, _.reverse))


console.log(f(['one', 'two', 'three']))

调试:

// 函数组合 调试 
// NEVER SAY DIE  --> never-say-die

const _ = require('lodash')

// const log = v => {
//   console.log(v)
//   return v
// }

const trace = _.curry((tag, v) => {
  console.log(tag, v)
  return v
})

// _.split()
const split = _.curry((sep, str) => _.split(str, sep))

// _.toLower()
const join = _.curry((sep, array) => _.join(array, sep))

const map = _.curry((fn, array) => _.map(array, fn))

const f = _.flowRight(join('-'), trace('map 之后'), map(_.toLower), trace('split 之后'), split(' '))

console.log(f('NEVER SAY DIE'))
lodash/fp
// lodash 的 fp 模块
// NEVER SAY DIE  --> never-say-die
const fp = require('lodash/fp')

const f = fp.flowRight(fp.join('-'), fp.map(fp.toLower), fp.split(' '))

console.log(f('NEVER SAY DIE'))
// lodash 和 lodash/fp 模块中 map 方法的区别
// const _ = require('lodash')

// console.log(_.map(['23', '8', '10'], parseInt))
// // parseInt('23', 0, array)
// // parseInt('8', 1, array)
// // parseInt('10', 2, array)


const fp = require('lodash/fp')

console.log(fp.map(parseInt, ['23', '8', '10']))
Point Free

Point Free:我们可以把数据处理的过程定义成与数据无关的合成运算,不需要用到代表数据的那个参数,只要把简单的运算步骤合成到一起,在使用这种模式之前我们需要定义一些辅助的基本运算函数.

// point free
// Hello     World => hello_world
const fp = require('lodash/fp')

const f = fp.flowRight(fp.replace(/\s+/g, '_'), fp.toLower)

console.log(f('Hello     World'))
// 把一个字符串中的首字母提取并转换成大写, 使用. 作为分隔符
// world wild web ==> W. W. W
const fp = require('lodash/fp')

// const firstLetterToUpper = fp.flowRight(fp.join('. '), fp.map(fp.first), fp.map(fp.toUpper), fp.split(' '))
const firstLetterToUpper = fp.flowRight(fp.join('. '), fp.map(fp.flowRight(fp.first, fp.toUpper)), fp.split(' '))

console.log(firstLetterToUpper('world wild web'))
Functor 函子

到目前为止已经已经学习了函数式编程的一些基础,但是我们还没有演示在函数式编程中如何把副作用控制在可控范围内、异常处理、异步操作等.
什么是函子:

// // Functor 函子
// class Container {
//   constructor (value) {
//     this._value = value
//   }

//   map (fn) {
//     return new Container(fn(this._value))
//   }
// }

// let r = new Container(5)
//   .map(x => x + 1)
//   .map(x => x * x)

// console.log(r)


class Container {
  static of (value) {
    return new Container(value)
  }

  constructor (value) {
    this._value = value
  }

  map (fn) {
    return Container.of(fn(this._value))
  }
}

// let r = Container.of(5)
//           .map(x => x + 2)
//           .map(x => x * x)

// console.log(r)


// 演示 null undefined 的问题
Container.of(null)
  .map(x => x.toUpperCase())

总结:

MayBe 函子
// MayBe 函子
class MayBe {
  static of (value) {
    return new MayBe(value)
  }

  constructor (value) {
    this._value = value
  }

  map (fn) {
    return this.isNothing() ? MayBe.of(null) : MayBe.of(fn(this._value))
  }

  isNothing () {
    return this._value === null || this._value === undefined
  }
}


// let r = MayBe.of('Hello World')
//           .map(x => x.toUpperCase())
// console.log(r)


// let r = MayBe.of(null)
//           .map(x => x.toUpperCase())
// console.log(r)


let r = MayBe.of('hello world')
          .map(x => x.toUpperCase())
          .map(x => null)
          .map(x => x.split(' '))
console.log(r)
Either 函子

Either 函子

   // Either 函子
class Left {
  static of (value) {
    return new Left(value)
  }

  constructor (value) {
    this._value = value
  }

  map (fn) {
    return this
  }
}

class Right {
  static of (value) {
    return new Right(value)
  }

  constructor (value) {
    this._value = value
  }

  map (fn) {
    return Right.of(fn(this._value))
  }
}

// let r1 = Right.of(12).map(x => x + 2)
// let r2 = Left.of(12).map(x => x + 2)

// console.log(r1)
// console.log(r2)


function parseJSON (str) {
  try {
    return Right.of(JSON.parse(str))
  } catch (e) {
    return Left.of({ error: e.message })
  }
}

// let r = parseJSON('{ name: zs }')
// console.log(r)

let r = parseJSON('{ "name": "zs" }')
          .map(x => x.name.toUpperCase())
console.log(r)
IO函子
// IO 函子
const fp = require('lodash/fp')

class IO {
  static of (value) {
    return new IO(function () {
      return value
    })
  }

  constructor (fn) {
    this._value = fn
  }

  map (fn) {
    return new IO(fp.flowRight(fn, this._value))
  }
}

// 调用
let r = IO.of(process).map(p => p.execPath)
// console.log(r)
console.log(r._value())
Task异步执行
// Task 处理异步任务
const fs = require('fs')
const { task } = require('folktale/concurrency/task')
const { split, find } = require('lodash/fp')

function readFile (filename) {
  return task(resolver => {
    fs.readFile(filename, 'utf-8', (err, data) => {
      if (err) resolver.reject(err)

      resolver.resolve(data)
    })
  })
}

readFile('package.json')
  .map(split('\n'))
  .map(find(x => x.includes('version')))
  .run()
  .listen({
    onRejected: err => {
      console.log(err)
    },
    onResolved: value => {
      console.log(value)
    }
  })
// IO 函子的问题
const fs = require('fs')
const fp = require('lodash/fp')

class IO {
  static of (value) {
    return new IO(function () {
      return value
    })
  }

  constructor (fn) {
    this._value = fn
  }

  map (fn) {
    return new IO(fp.flowRight(fn, this._value))
  }
}

let readFile = function (filename) {
  return new IO(function () {
    return fs.readFileSync(filename, 'utf-8')
  })
}

let print = function (x) {
  return new IO(function () {
    console.log(x)
    return x
  })
}

let cat = fp.flowRight(print, readFile)
// IO(IO(x))
let r = cat('package.json')._value()._value()
console.log(r)
monad 函子

解决函子嵌套问题

// IO Monad
const fs = require('fs')
const fp = require('lodash/fp')

class IO {
  static of (value) {
    return new IO(function () {
      return value
    })
  }

  constructor (fn) {
    this._value = fn
  }

  map (fn) {
    return new IO(fp.flowRight(fn, this._value))
  }

  join () {
    return this._value()
  }

  flatMap (fn) {
    return this.map(fn).join()
  }
}

let readFile = function (filename) {
  return new IO(function () {
    return fs.readFileSync(filename, 'utf-8')
  })
}

let print = function (x) {
  return new IO(function () {
    console.log(x)
    return x
  })
}

let r = readFile('package.json')
          // .map(x => x.toUpperCase())
          .map(fp.toUpper)
          .flatMap(print)
          .join()

console.log(r)
总结:
总结

文章内容输出来源于:拉勾教育大前端高薪训练营

上一篇 下一篇

猜你喜欢

热点阅读