3

I wrote a function with Haskell to extract some values from this data type :

data Result = ResuVal Double     
              | ResuValIdx Double (Maybe Int)   
              | ResuValCpt Double Int           
              | NoResu                  
              deriving (Show)

This function extract the Int values in the Result data type and concatenate them in a list.

catIdxCpt :: [Result] -> [Int]
catIdxCpt [] = []
catIdxCpt (x:xs) = case x of
                ResuValIdx v (Just i) -> i:catIdxCpt xs
                ResuValCpt v c -> c:catIdxCpt xs      
                _ -> catIdxCpt xs  

This function is working well but I first tried to wrote it with a comprehension list such as :

catIdxCpt ls = [i | ResuValIdx v (Just i)  <- ls  ]

or

catIdxCpt ls = [i | ResuValIdx v (Just i)  <- ls | ResuValCpt v i  <- ls ]

and other combinations. But I didn't managed to have the expected result.

Do you know how to built (if it is possible) the catIdxCpt function with a list comprehension ?

1
  • Interesting side note: The last version of the comprehension ([i | ... | ... ]) can actually be used to zipWithN several lists via the ParallelListComprehension extension. Doesn't help here, but it has its uses. Commented Aug 17, 2016 at 7:29

2 Answers 2

4

Your function involves both mapping and filtering, so consider this technique:

foo xs = [ y | Just y <- map go xs ]
  where go (ResuValIdx _ (Just i)) = Just i
        go (ResuValCpt v c)        = Just c
        go _                       = Nothing

The helper function go returns Nothing for elements you want to remove.

The pattern Just y <- zs will select only those elements from the list zs which match the pattern Just y.

Sign up to request clarification or add additional context in comments.

Comments

1
[x | l <- ls, x <- [i | ResuValIdx v (Just i) <- [l]] ++ [i | ResuValCpt v i <- [l]]]

Alternatively, consider:

{-# LANGUAGE LambdaCase #-}

catIdxCpt :: [Result] -> [Int]
catIdxCpt = mapMaybe $ \case
  ResuValIdx v (Just i) -> Just i
  ResuValCpt v c -> Just c
  _ -> Nothing

1 Comment

The first answer manages to make the code half as efficient and a third as readable for the sake of ... ummm...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.