###markdown
// 使用Object.freeze实现浅不可变
const immutableObj = Object.freeze({ count: 0 });
// 更新时创建新对象
const newObj = { ...immutableObj, count: immutableObj.count + 1 };
-- Haskell中使用Data.Map
import qualified Data.Map as Map
let m1 = Map.fromList [("a",1), ("b",2)]
let m2 = Map.insert "c" 3 m1 -- 创建新map而非修改原map
// Scala中使用State Monad
case class State[S, A](run: S => (A, S)) {
def flatMap[B](f: A => State[S, B]): State[S, B] =
State(s => {
val (a, s1) = run(s)
f(a).run(s1)
})
}
原因: 频繁创建新对象可能导致内存压力 解决方案:
原因: I/O操作本质是有状态的 解决方案:
// 使用IO Monad隔离副作用
class IO<A> {
constructor(public unsafePerformIO: () => A) {}
static of<B>(b: B): IO<B> {
return new IO(() => b);
}
map<B>(f: (a: A) => B): IO<B> {
return new IO(() => f(this.unsafePerformIO()));
}
}
没有搜到相关的文章