ZelelB
ZelelB

Reputation: 2000

How to extract an element from a tuple in haskell

I have the following tuples:

type Id = Int
type Name = String
type FSK = Int
type Movie = (Id, Name, FSK)

now I want to define a function that extracts a movie from a given list like that:

extract :: Id -> [Movie] -> (Maybe Movie, [Movie])
extract = .... ?? 

so that when I give an id and a list of Movies, it extracts: 1) Nothing +the given list, if the id is found 2) Just + the movie , and the new list without that movie, if the given id is found, and the movie is deleted from the list

example:

*Main> extract 0 [(1,"Matrix",16),(2,"Gladiator",0)]
(Nothing,[(1,"Matrix",16),(2,"Gladiator",0)])
*Main> extract 1 [(1,"Matrix",16),(2,"Gladiator",0)]
(Just (1,"Matrix",16),[(2,"Gladiator",0)])

How should I define the function?

Upvotes: 0

Views: 944

Answers (1)

Diligent Key Presser
Diligent Key Presser

Reputation: 4253

extract :: Id -> [Movie] -> (Maybe Movie, [Movie])
extract id []                 = (Nothing, [])
extract id ((fid, n, f):list) | fid == id =  (Just (fid, n, f), list)
                              | otherwise =  (found, (fid, n, f):tail)
                              where (found, tail) = extract id list

Upvotes: 3

Related Questions