Clojure equivalent of Haskell's "Scrap Your Boilerplate" (SYB)
Asked Answered
T

2

11

I found an interesting library in Haskell called Scrap Your Boilerplate based on a paper by Simon Peyton Jones which seems like an effective way to write code that can update large, deeply nested data structures in a functional programming language. It enables code like:

incS :: Float -> Salary -> Salary
incS k (S s) = S (s * (1+k))

increase :: Float -> Company -> Company
increase k = everywhere (mkT (incS k))

Which effectively increases the salary by a fixed proportion k for everyone in a potentially large and complex Company data structure.

Is there an equivalent library or approach to achieve the same kind of programming style in Clojure?

For example, how could I write the Clojure equivalent of the example used above:

(defn increase [company k]
  (everywhere-in company (transform-map-values :salary #(* % (+ 1 k))))
Theophrastus answered 11/9, 2011 at 5:54 Comment(2)
The SYB papers were a continuation of co-author Ralf Lämmel's work on embedding Stratego in Haskell with (different) co-author Joost Visser. To update nested structures in Clojure you would need the "traversal control" side of SYB more than its datatype generics side, so you could widen your question to ask if anyone has embedded Stratego in Clojure. I don't know Clojure and a bit of web searching seems to suggest no-one has done this yet. There are certainly embeddings of the Stratego traversals in Scheme which should be easier to port than SYB, I've written one myself.Vadnee
I don't know SYB, but maybe clojure.walk is what you are looking for?Imprinting
O
4

The closest to this in Clojure is probably the "in" functions (assoc-in, update-in, dissoc-in).

These functions allow you to do deeply nested, pinpoint changes in clojure. There is no equivalent to these functions in Haskell because they rely heavily on dynamic typing.

Odense answered 12/9, 2011 at 15:41 Comment(0)
R
1

They weren't around when this question was first asked, but I believe transducers enable a similar style of programming. Basically transducible processes implement a certain set of functions, which transducers can use to traverse over any transducible process.

Reckless answered 30/1, 2015 at 21:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.