user5591265
user5591265

Reputation:

A new data type element access in Haskell

I am new with haskell. I have new types:

type RealName = String
type UserName = String
type GroupName = String
type Message = String

and

data User = User UserName RealName [UserName] [Post]

and in a new function I want to access the real name of a user;

accreal :: User -> RealName
accreal us = ??

How can I do it, I tried many ways but didnt work.

Upvotes: 1

Views: 1091

Answers (1)

chi
chi

Reputation: 116139

Just use pattern matching:

accreal:: User -> RealName
accreal (User un rn uns ps) = rn

You might also want to prefix unused variables with _ to suppress warnings.

accreal:: User -> RealName
accreal (User _un rn _uns _ps) = rn

You can also simply use _ to discard a value, e.g. accreal (User _ rn _ _) = rn.

Alternatively, change your data type into a record:

data User = User 
   { user :: UserName
   , real :: RealName
   , others :: [UserName]
   , posts :: [Post] }

This automatically defines a projection real :: User -> RealName for you.

Upvotes: 6

Related Questions