Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7011779
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T22:10:13+00:00 2026-05-27T22:10:13+00:00

Say I have the following record: data Rec = Rec { field1 :: Int,

  • 0

Say I have the following record:

data Rec = Rec {
   field1 :: Int,
   field2 :: Int
}

How do I write the function:

changeField :: Rec -> String -> Int -> Rec
changeField rec fieldName value 

such that I can pass in the strings “field1” or “field2” into the fieldName argument and have it update the associated field? I understand Data.Data and Data.Typeable are what to use here but I can’t figure these two packages out.


An example of a library I’ve seen do this is cmdArgs. Below is an excerpt from a blog posting on how to use this library:

{-# LANGUAGE DeriveDataTypeable #-}
import System.Console.CmdArgs

data Guess = Guess {min :: Int, max :: Int, limit :: Maybe Int} deriving (Data,Typeable,Show)

main = do
    x <- cmdArgs $ Guess 1 100 Nothing
    print x

Now we have a simple command line parser. Some sample interactions are:

$ guess --min=10
NumberGuess {min = 10, max = 100, limit = Nothing}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T22:10:14+00:00Added an answer on May 27, 2026 at 10:10 pm

    OK, here’s a solution that doesn’t use template haskell, or require you to manage the field map manually.

    I implemented a more general modifyField which accepts a mutator function, and implemented setField (nee changeField) using it with const value.

    The signature of modifyField and setField is generic in both the record and mutator/value type; however, in order to avoid Num ambiguity, the numeric constants in the invocation example have to be given explicit :: Int signatures.

    I also changed the parameter order so rec comes last, allowing a chain of modifyField/setField to be created by normal function composition (see the last invocation example).

    modifyField is built on top of the primitive gmapTi, which is a ‘missing’ function from Data.Data. It is a cross between gmapT and gmapQi.

    {-# LANGUAGE DeriveDataTypeable #-}
    {-# LANGUAGE RankNTypes #-}
    
    import Data.Typeable (Typeable, typeOf)
    import Data.Data (Data, gfoldl, gmapQi, ConstrRep(AlgConstr),
                      toConstr, constrRep, constrFields)
    import Data.Generics (extT, extQ)
    import Data.List (elemIndex)
    import Control.Arrow ((&&&))
    
    data Rec = Rec {
        field1 :: Int,
        field2 :: String
    } deriving(Show, Data, Typeable)
    
    main = do
      let r = Rec { field1 = 1, field2 = "hello" }
      print r
      let r' = setField "field1" (10 :: Int) r
      print r'
      let r'' = setField "field2" "world" r'
      print r''
      print . modifyField "field1" (succ :: Int -> Int) . setField "field2" "there" $ r
      print (getField "field2" r' :: String)
    
    ---------------------------------------------------------------------------------------
    
    data Ti a = Ti Int a
    
    gmapTi :: Data a => Int -> (forall b. Data b => b -> b) -> a -> a
    gmapTi i f x = case gfoldl k z x of { Ti _ a -> a }
      where
        k :: Data d => Ti (d->b) -> d -> Ti b
        k (Ti i' c) a = Ti (i'+1) (if i==i' then c (f a) else c a)
        z :: g -> Ti g
        z = Ti 0
    
    ---------------------------------------------------------------------------------------
    
    fieldNames :: (Data r) => r -> [String]
    fieldNames rec =
      case (constrRep &&& constrFields) $ toConstr rec of
        (AlgConstr _, fs) | not $ null fs -> fs
        otherwise                         -> error "Not a record type"
    
    fieldIndex :: (Data r) => String -> r -> Int
    fieldIndex fieldName rec =
      case fieldName `elemIndex` fieldNames rec of
        Just i  -> i
        Nothing -> error $ "No such field: " ++ fieldName
    
    modifyField :: (Data r, Typeable v) => String -> (v -> v) -> r -> r
    modifyField fieldName m rec = gmapTi i (e `extT` m) rec
      where
        i = fieldName `fieldIndex` rec
        e x = error $ "Type mismatch: " ++ fieldName ++
                                 " :: " ++ (show . typeOf $ x) ++
                               ", not " ++ (show . typeOf $ m undefined)
    
    setField :: (Data r, Typeable v) => String -> v -> r -> r
    setField fieldName value = modifyField fieldName (const value)
    
    getField :: (Data r, Typeable v) => String -> r -> v
    getField fieldName rec = gmapQi i (e `extQ` id) rec
      where
        i = fieldName `fieldIndex` rec
        e x = error $ "Type mismatch: " ++ fieldName ++
                                 " :: " ++ (show . typeOf $ x) ++
                               ", not " ++ (show . typeOf $ e undefined)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Say I have the following class MyComponent : IMyComponent { public MyComponent(int start_at) {...}
Say I have the following string: I am the most foo h4ck3r ever!! I'm
Let's say I have a database filled with people with the following data elements:
Let's say I have the following data model, for keeping track of the stats
Let's say I have the following data in a decimal (18,9) identity column in
Let's say I have the following database table: record_id | record_date | record_value -----------+-------------+--------------
Let's say we have following this: <p class=first>This is paragraph 1.</p> <p class=second>This is
Say we have the following method: private MyObject foo = new MyObject(); // and
Say I have the following file structure: app/ app.py controllers/ __init__.py project.py plugin.py If
Say I have the following methods: def methodA(arg, **kwargs): pass def methodB(arg, *args, **kwargs):

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.