Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over record fields?

I have following datatype defined as record

data Config = Config
  { field1 :: String
  , field2 :: String
  , field3 :: String
  }

I want to iterate over each field of Config, apply some function String -> String, for example tail and get in return new Config.

What is idiomatic way to do this? Preferably, without heavy 3rd party libraries.

like image 776
Filip van Hoft Avatar asked Oct 07 '15 17:10

Filip van Hoft


1 Answers

Well, the best way to do it would probably be

{-# LANGUAGE DeriveFunctor #-}

type Config = Config' String
data Config' a = Config
  { field1 :: a
  , field2 :: a
  , field3 :: a
  } deriving (Functor)

configHeads :: Config -> Config' Char
configHeads = fmap head
like image 68
leftaroundabout Avatar answered Oct 06 '22 06:10

leftaroundabout