Is there an object-identity-based, thread-safe memoization library somewhere?

前端 未结 3 1483
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 15:11

I know that memoization seems to be a perennial topic here on the haskell tag on stack overflow, but I think this question has not been asked before.

I\'m aware

3条回答
  •  一生所求
    2021-02-07 15:16

    If you only want to memoize based on object identity, and not equality, you can just use the existing laziness mechanisms built into the language.

    For example, if you have a data structure like this

    data Foo = Foo { ... }
    expensive :: Foo -> Bar
    

    then you can just add the value to be memoized as an extra field and let the laziness take care of the rest for you.

    data Foo = Foo { ..., memo :: Bar }
    

    To make it easier to use, add a smart constructor to tie the knot.

    makeFoo ... = let foo = Foo { ..., memo = expensive foo } in foo
    

    Though this is somewhat less elegant than using a library, and requires modification of the data type to really be useful, it's a very simple technique and all thread-safety issues are already taken care of for you.

提交回复
热议问题