Someone can help me in haskell [closed]

The expression:

negative :: [Int] -> Int
negative list = [ x | x <- list, if list<0 then x=1 else x=0]

Makes no sense for several reasons:

  1. the result type is an Int, so by using list comprehension as outer expression, you are generating a list;
  2. x is an element of the list x <- list, if list < 0 then … else … makes no sense since list is a list, and can not be compared with a single element; and
  3. variables can not be assigned a new value. Variables are defined once, here by x <- list. You can make a more locally scoped variable with the same name, but that is not a good idea here.

You can just use filter :: (a -> Bool) -> [a] -> [a] here to filter the list and only retain the elements less than 0 and then calculate the length :: Foldable f => f a -> Int:

negative :: [Int] -> Int
negative list = length (filter (< 0) list)

we can make these point-free, and let this work with any Num type:

negative :: (Num a, Ord a) => [a] -> Int
negative = length . filter (< 0)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top