Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "setter" type of Record

Tags:

haskell

If I have a record like this:

data PersonR = PersonR { firstName :: String
                       , lastName :: String
                       } deriving Show

And wanting to check firstName's type:

firstName :: PersonR -> String

But this would be a typical getter in OOP. Since in Haskell variables are immutable, how can I see the setter with the :t command? I am assuming it would be:

:: PersonR -> String -> PersonR

But how can I get this?

like image 847
Rui Peres Avatar asked Dec 06 '14 22:12

Rui Peres


1 Answers

Haskell doesn't define a setter function for you. The best approximation is a special syntax which allows you to conveniently create a new record from an old one while altering certain fields.

Example:

john = PersonR "John" "Doe"  -- same as PersonR { firstName = "John", lastName = "Doe" }

jane = john { firstName = "Jane" }

The value jane is now equal to Person "Jane" "Doe".

Using this syntax you can create your own setter function:

setLastName :: PersonR -> String -> PersonR
setLastName person surname = person { lastName = surName }

but you might find it just as convenient to use the special syntax itself.

like image 112
ErikR Avatar answered Oct 19 '22 04:10

ErikR