【问题标题】:OO to functional — learning from everyday problemOO 到功能——从日常问题中学习
【发布时间】:2021-01-14 06:53:37
【问题描述】:

我正要学习使用 fp-ts 的函数式编程,我只是在问自己,将这样的东西“转换”为函数式范式的正确函数式方法是什么:

//OOP:

interface Item {
  name: string;
}

class X {
  private readonly items: { [s:string]: Item[] } = {};

  add(i: Item): Item {
    if(!this.items.hasOwnProperty(i.name))
      this.items[i.name] = [];

    if(this.items[i.name].indexOf(i) < 0)    
      this.items[i.name].push(i);

    return i;
  }
}

所以,我想我应该走这条路:

import * as O from 'fp-ts/es6/Option';
import * as E from 'fp-ts/es6/Either';

// using interfaces from above

interface state {
  items: { [s:string]: Item[] }
}

export const createState = (): State => ({ items: {} });


export const add = (s: State, i: Item) => pipe(
  // using IO here?
  E.fromPredicate(
    () => s.hasOwnProperty(i.name),
    () => []
  )
  
    
)

// to use it:

import { createState, add } from './fx';

let state = createState();

// update
state = add(state, {name: 'foo'})

既然add()操作涉及到状态的修改,是不是应该依赖IO呢?如果add返回一个新的状态对象,它是一个纯函数,所以不需要使用IO?所以我在这里提出的问题可能有点宽泛,但是:这里推荐的技术/模式是什么?

【问题讨论】:

  • 看看redux js是如何工作的

标签: typescript functional-programming fp-ts


【解决方案1】:

既然add()操作涉及到状态的修改,是否应该依赖IO?

是的,add() 不会返回任何东西,但有状态效果,所以它应该返回IO&lt;void&gt;

如果add返回一个新的状态对象,它是一个纯函数,所以不需要使用IO?

正确。

这里推荐的技术/模式是什么?

函数式程序员通常不惜一切代价避免可变状态。

您尝试实现的是写时复制多图。你不应该需要来自fp-ts 的任何东西。

type MyItem = { name: string };

// we've made the store polymorphic
type MyObj<Item> = { [s: string]: Item[] };

// this is only necessary if you want to expose an implementation-independent api.
export const empty = {};

// i before o, in case we want currying later, o will change more.
const add = <Item>(k: string, v: Item, o: MyObj<Item>) => 
  // abuse the spread operator to get create a new object, and a new array
  ({ ...o, [k]: [v, ...(o[k] || [])] });

// specialization for your item's case
export const addMyItem = (i: MyItem, o: MyObj<MyItem>) => add(i.name, i, o);

你可以这样做:

const a = addMyItem({ name: "test" }, addMyItem({ name: "test" }, empty));

【讨论】:

    猜你喜欢
    • 2011-02-09
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    相关资源
    最近更新 更多