CodingGuy
CodingGuy

Reputation: 11

Haskell multiply arguments if odd

I want my code to read numbers from the console arguments and write the even ones back to the console. The odd ones should be multiplied by 2 to make them even as well. For this I added the method evenify which checks with mod 2 if its odd or even.

I just can't find the error I'm making, most likely it's just a syntax error somewhere. Here is my code as of now:

import System.Environment

evenify :: [Integer] -> [Integer]
evenify n = if mod n 2 == 0 then n else n*2
main :: IO ()
main = getArgs >>= putStrLn . show . evenify . read . head
_ = main

What is the error?

Upvotes: 1

Views: 214

Answers (2)

ErikR
ErikR

Reputation: 52029

First problem is that evenify has the wrong type signature - as written it has the signature:

evenify :: Integer -> Integer

With this change your program works in the sense that it will process one command line argument - the first one only.

To process all of the arguments use map:

main = do args <- getArguments
          putStrLn $ show $ map evenify (map read args)

Explanation:

args                         is the list of command line arguments (Strings)
map read args                is a list of Integers
map evenify (map read args)  is the list of results

Upvotes: 2

karakfa
karakfa

Reputation: 67467

first error that catches the eye

evenify :: [Integer] -> [Integer]
evenify n = if mod n 2 == 0 then n else n*2

signature expects a list but implementation is for scalars.

Upvotes: 1

Related Questions