3

我正要学习使用函数式编程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?所以我在这里提出的问题可能有点宽泛,但是:这里推荐的技术/模式是什么?

4

1 回答 1

1

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

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

如果 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));
于 2021-01-14T12:17:45.680 回答