Reputation: 679
I have written following data type and its instance in Haskell:
data Plaster = Plaster [String] deriving (Read, Show)
examplePlaster :: Plaster
examplePlaster = Plaster ["..AEG", "..CD", "DC...", "A.B.", "..EFG"]
I would like to create a function, which applicated to examplePlaster
returns the first String on a list. How should I do that?
Upvotes: 0
Views: 75
Reputation: 532208
Like any other type, you can pattern match on the value created by your data constructor.
getFirst :: Plaster -> Maybe String
getFirst (Plaster (x:xs)) = Just x
getFirst (Plaster []) = Nothing
Upvotes: 6
Reputation: 4481
You could use the head
function from Data.List
getFirst :: Plaster -> String
getFirst (Plaster []) = ""
getFirst (Plaster xs) = head xs
Where head :: [a] -> a
extract the first element of a list, which must be non-empty. As explained here.
And to call it do: getFirst examplePlaster
Upvotes: 1