Haskell data type dynamic change

I have a haskell template that looks something like this:

data Configuration { confA :: Integer , confB :: Boolean , confC :: String } x = (\arg opt -> opt{ confA=arg }) y = (\arg opt -> opt{ confB=arg }) z = (\arg opt -> opt{ confC=arg }) 

and I would like to remove the template so that something gives in the following lines:

 setter :: (Config -> a) -> a -> Config -> Config x = setter confA y = setter confB z = setter confC 

But I have no idea how to build such a setter function. Is this possible in (without a template) haskell, or am I against using the sugar syntax here? If so, how can I do such a thing in a haskell template?

+6
source share
2 answers

This is not possible with the Haskell system alone. You need lenses; this previous stack overflow question , and its correct answer is a good introduction. Personally, I use the data-lens package that they talked about there. (See Also data-lens-fd to use it with MonadState from mtl - if you don't know what it is, just know that you should probably use it when you want to use lenses in the State monad.)

The data-lens-template package may be the Template Haskell application you want; it defines lens definitions for recording fields.

Another popular fclabels lens package . I prefer a data lens for its simplicity and speed; fclabels (since version 1.0) is a bit more flexible, but you don't need that kind of flexibility for what you want to do. (Note that due to its new flexibility, the fclabels (:->) can no longer be directly translated to a simple lens definition, as indicated in the "Stack Overflow" answer I linked.)

+13
source

This is not possible without a Haskell template. You can use the data access pattern and data access pattern to remove such a boiler plate.

+1
source

Source: https://habr.com/ru/post/903790/


All Articles