如何从haskell中的元组中提取元素

时间:2014-10-29 02:06:16

标签: list haskell tuples

我有以下元组:

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

现在我想定义一个从给定列表中提取电影的功能:

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

所以当我给出一个id和一个电影列表时,它会提取: 1)如果找到id,则没有+给定列表 2)只是+电影,没有那部电影的新列表,如果找到给定的id,并且电影从列表中删除

示例:

*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)])

我该如何定义这个功能?

1 个答案:

答案 0 :(得分:3)

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