user3726947
user3726947

Reputation: 531

read integers and return number of inputs satisfying certain condition

Im trying to write a little program in haskell that takes integers as inputs until a certain condition, say P, is fulfilled and then prints out the number of all elements which fulfill a condition Q. My code is the following

list = []
main :: IO ()
main = do
    x <- getLine
    read x : list
    if (P) then putStrLine "length (filter Q list)" else main

But im getting the error „illegal escape sequence“. Could somebody give some advice how to solve this? I guess the problem is that i can’t recursively call the main function? thanks in advance.

Upvotes: 0

Views: 37

Answers (1)

Random Dev
Random Dev

Reputation: 52290

this is what I can take away from your description:

readIn :: (Integer -> Bool) -> IO [Integer]
readIn stop = do
  i <- read <$> getLine
  if stop i then return [] else do
    rest <- readIn stop
    return (i:rest)

main :: IO ()
main = do
  xs <- readIn (> 10)
  print (length (filter even xs))

as you can see I refactored out the reading of the input list (note that I did not handle bad-formatted input like "noNumber" - it will only work if you input something that can be read into Integer) with readIn

The first argument to readIn is just your P - as an example I used (> 10) so it will stop asking for more if you enter a number bigger than 10.

the rest is just using List.filter together with length to get your "number of all elements wich fulfill a condition" - I used even as an example for such

example run

λ> :main
3
4
5
6
7
8
9
10
11
4 -- this is the result

Upvotes: 4

Related Questions