haskelltuplesaccumulator

How to check in a tuple if element matches?


I am trying to check whether my second part of my tuple is 1.0 and if it is then I am storing it in the list. But I can't figure out how to implement the check.

number :: [(Integer, Double)] -> [Integer]
number lst = number' lst []
 where 
  number' [] a = a
  ((mat,1.0): xs) a = number'(xs) (mat:a) -- Here I am getting my error
  ((_,lst): xs) a = number'(xs) a

Maybe someone has an idea.


Solution

  • The reason this doesn't work is because you need to write number' for every line:

    number :: [(Integer, Double)] -> [Integer]
    number lst = number' lst []
     where 
      number' [] a = a
      number' ((mat,1.0): xs) a = number'(xs) (mat:a)
      number' ((_,lst): xs) a = number'(xs) a
    

    But this will return the "keys" in reverse.

    You can pattern match with:

    number :: (Eq a, Num a) => [(a, b)] -> [a]
    number ((x, 1):xs) = x : number xs
    number (_:xs) = number xs
    number [] = []
    

    You can however work with list comprehension:

    number :: (Eq a, Num a) => [(a, b)] -> [a]
    number xs = [ x | (x, 1) <- xs ]
    

    or with a combination of map and filter:

    number :: (Eq a, Num a) => [(a, b)] -> [a]
    number = map fst . filter ((1 ==) . snd)