这是一个函子吗
Is this a Functor
最近在学习函子和单子,但似乎有点混乱。我写这个是为了链接多个操作,想知道它是否是一个函子,我理解正确吗?
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
我不这么认为,因为 Functors 必须保留组合 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
)
最近在学习函子和单子,但似乎有点混乱。我写这个是为了链接多个操作,想知道它是否是一个函子,我理解正确吗?
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
我不这么认为,因为 Functors 必须保留组合 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
)