Will
Will

Reputation: 9

haskell function not working, can anyone tell me why?

I am trying to tell the user if a given number is even or odd, but it doen't seem to work...

typeOfInt :: Int -> String

typeOfInt integerValue
  |integerValue `mod` 2 == 0 = "even number"
  |otherwise = "odd number"

typeOfInt 27

Upvotes: 0

Views: 1135

Answers (1)

Diego Vicente
Diego Vicente

Reputation: 375

The code itself it's ok and works, but it looks like you tried to evaluate the function in a Pythonic way, not exactly how you should use the functions in Haskell. You have to options here:

  1. Using the REPL, by running ghci in the directory and then loading the file inside it (using the command :l <filename>.hs). Once in there, you can use the function interactively, by calling it like you are doing inside the file (typeOfInt 27) or with other functions (map typeOfInt [1, 2, 3, 4, 5]).

  2. Creating a main method and compiling the file. The main method in Haskell has to be a main :: IO () method, and that is what will be executed once you run a compiled file.

For your example, you can use putStrLn to get the results that you seem to be looking for:

main :: IO ()
main = putStrLn $ typeOfInt 27

As you can see, in this case it is arguably more useful to use the ghci and play with the functions instead of compiling.

Upvotes: 7

Related Questions