【问题标题】:Is this a Functor这是一个函子吗
【发布时间】:2021-09-27 09:32:35
【问题描述】:

最近我在学习函子和单子,但似乎有点混乱。我写了这个来链接多个操作,想知道它是否是一个仿函数并且我理解正确吗?

function Init(store = {}) {
  const map = (fn) => {
    const result = fn(store)
    return Init(result ? {...store, ...result} : store)
  }
  const unwrap = () => store
  return {
    map,
    unwrap
  }
}

// example usage
Init()
.map(fetchData)
.map(fetchOtherData)
.map(compareTwoData)
.map(saveAllData)
// ...etc

【问题讨论】:

  • "functor" 是什么意思? AFAIK 有不同的定义,我从未在 JavaScript 的上下文中听说过这个术语。标签functor 包含多个定义。 “1. 函数对象。在面向对象的语言中,它是一种允许对象像普通函数一样使用的特性。” 对于 JavaScript 中的所有函数都是如此。每个函数都是一个对象。
  • @jabaa Functor
  • @VLAZ 这是数学上下文,但我看不到与发布代码的关系。
  • @jabaa 函数式编程有一个叫做“函子”的概念,它与数学概念密切相关。这也是 OP 在这里展示的。
  • @VLAZ 你的意思是这个链接Functor

标签: javascript functional-programming functor


【解决方案1】:

我不这么认为,因为 Functor 必须保留组合 map(g°h)=map(g)°map(h),而你的却没有:

function Init(store = {}) {
    const map = (fn) => {
        const result = fn(store)
        return Init(result ? {...store, ...result} : store)
    }
    const unwrap = () => store
    return {
        map,
        unwrap
    }
}

a = x => ({...x, a:1})
b = x => 0


console.log(Init({X:1}).map(a).map(b).unwrap())
console.log(Init({X:1}).map(x => b(a(x))).unwrap())

这是一个满足两个函子定律的基本函子示例:

function Functor(value) {
    const fmap = (fn) => {
        const result = fn(value)
        return Functor(result)
    }
    return {fmap, value}
}

//

let id = x => x
let a = x => x * 5
let b = x => x + 3


// identity
console.log(
    Functor(7).value === Functor(7).fmap(id).value
)

// composition
console.log(
    Functor(7).fmap(a).fmap(b).value ===
    Functor(7).fmap(x => b(a(x))).value
)

【讨论】:

  • 非常感谢。是这样吗?它看起来比教程简单得多。 fmap 代表平面地图吗?你也可以举一个简单的 Monad 例子吗?
  • fmap 是通用 Functor 映射的名称,以区别于仅适用于列表的普通 map
  • @user8190223 georg 的函子只是身份函子,即它提供了足够的结构来成为函子,但没有做一些特别的事情。当您查看 id 仿函数时,您所学到的只是类型需要正式成为仿函数。但函子的真正威力在于每个函子编码的特殊语义,除了 id 函子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2016-12-10
相关资源
最近更新 更多