Haskell Program to convert primitive types to objects


In Haskell, we will convert primitive types to objects by using accessor functions along with getName function, constructors and record syntax. In the first example, we are going to use (getName person = name person) and in the second example, we are going to use (getName (Person name _) = name and getAge (Person _ age) = age). And in the third example, we are going to use record syntax.

Algorithm

  • Step 1 − The ‘Person’ data type is defined with two fields I.e., Name and Age.

  • Step 2 − The getName function is defined

  • Step 3 − The program execution will be started from main function. The main() function has whole control of the program. It is written as main = do.

  • Step 4 − The object named, “p” is being initialized with a name and an age using constructor.

  • Step 5 − The resultant name and age of the Person object is printed to the console using ‘putStrLn’ statement once the function is called.

Example 1

In this example, we define a Person data type with two fields: name of type String and age of type Int. We also define a getName function that takes a Person object and returns its name field.

data Person = Person { name :: String, age :: Int }

getName :: Person -> String
getName person = name person

main :: IO ()
main = do
   let p = Person { name = "Alice", age = 30 }
   putStrLn $ "Name: " ++ getName p
   putStrLn $ "Age: " ++ show (age p)

Output

Name: Alice
Age: 30

Example 2

In this example, we define a Person data type using a constructor that takes two arguments: a String representing the person's name and an Int representing their age.

data Person = Person String Int

getName :: Person -> String
getName (Person name _) = name

getAge :: Person -> Int
getAge (Person _ age) = age

main :: IO ()
main = do
   let p = Person "Alice" 30
   putStrLn $ "Name: " ++ getName p
   putStrLn $ "Age: " ++ show (getAge p)

Output

Name: Alice
Age: 30

Example 3

In this example, we define a Person data type with two fields: getName of type String and getAge of type Int. The getName and getAge fields are defined using the record syntax, which automatically generates accessor functions with the same names as the fields.

data Person = Person { getName :: String, getAge :: Int }

main :: IO ()
main = do
   let p = Person { getName = "Alice", getAge = 30 }
   putStrLn $ "Name: " ++ getName p
   putStrLn $ "Age: " ++ show (getAge p)

Output

Name: Alice
Age: 30

Conclusion

In Haskell, primitive types such as Int, Double, and Bool are represented as values rather than objects. However, it is possible to create custom data types that wrap these primitive types and provide additional functionality through methods. In Haskell, we can use accessor functions , constructors and record syntax for such conversions.

Updated on: 25-Apr-2023

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements