Hajra Zamir
Hajra Zamir

Reputation: 1

Read a list of INT type from the console and print out only even numbers out of the given list Using list comprehension

I'm very new to functional programming with Haskell, I have started learning it a few days ago by doing a few tasks.

I'm trying to write a function that will Read a list of INT type from the console and print out only even numbers out of the given list Using list comprehension. This is what I have:

[x | x <- [nums], x == even, x <= 50]

Upvotes: 0

Views: 764

Answers (1)

Jon Purdy
Jon Purdy

Reputation: 54971

What you have written has a couple of minor errors:

[x | x <- [nums], x == even, x <= 50]
  1. x <- [nums] will bind x to each element of the list [nums] :: [[Int]], which has one element, nums :: [Int]. Presumably you wanted x <- nums, so that x :: Int.

  2. x == even attempts to compare x, which has type Int, to the function even, which has type Integral a => a -> Bool (or, simplified a bit, Int -> Bool). You can’t compare values of different types for equality, nor can you compare functions; what you want to do is call the function even on x with even x.

With those changes, your expression will work without error:

[x | x <- nums, even x, x <= 50]

Now, as for reading the values from the console, you would do that from main since it requires IO:

main :: IO ()
main = do
  putStrLn "Enter space-separated list of numbers."
  line <- getLine
  let nums = map read (words line) :: [Int]
  print [x | x <- nums, even x, x <= 50]

This uses words to split the line on whitespace, map read to convert each string in the resulting list to an Int, and finally your list comprehension to calculate the output. Now, input such as 10 25 30 45 50 60 will produce output such as [10,30,50].

A couple of exercises to improve your understanding:

  • Move the prompt, parsing, and list comprehension into separate top-level function definitions with type signatures.

  • What happens when the user enters invalid input like 10, 20, foo? How could you handle this error?

Upvotes: 1

Related Questions