When manipulating immutable datastructures, what's the difference between Clojure's assoc-in and Haskell's lenses?

前端 未结 4 1398
名媛妹妹
名媛妹妹 2021-02-18 22:45

I need to manipulate and modify deeply nested immutable collections (maps and lists), and I\'d like to better understand the different approaches. These two libraries solve more

4条回答
  •  清酒与你
    2021-02-18 23:36

    You're talking about very two different things.

    You can use lens to solve similar problems as assoc-in, where you're using collection types (Data.Map, Data.Vector) that match the semantics but there are differences.

    In untyped languages like Clojure it's common to structure your domain data in terms of collections that have non-static contents (hash-maps, vectors, etc) even when it's modeling data that is conventionally static.

    In Haskell you would structure your data using a record and ADTs, where while you can express contents that might or might not exist (or wrap a collection), the default is statically known contents.

    One library to look at would be http://hackage.haskell.org/package/lens-aeson where you have JSON documents which have possibly varying contents.

    The examples demonstrate that when your path and type doesn't match the structure/data, it kicks out a Nothing instead of Just a.

    Lens doesn't do anything beyond provide sound getter/setter behavior. It doesn't express a particular expectation about how your data looks, whereas assoc-in only makes sense with associative collections with possibly non-deterministic contents.

    Another difference here is purity and laziness vs. strict and impure semantics. In Haskell, if you never used the "older" states, and only the most recent one, then only that value will be realized.

    tl;dr lenses as found in Lens and other similar libraries are more general, more useful, type-safe, and especially nice in lazy/pure FP languages.

提交回复
热议问题