Reputation: 2000
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
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