Jordan
Jordan

Reputation: 35

Haskell, doing some code followed by an if statement in one function

I've been using haskell for roughly a week now and I don't seem to understand how to add a line of code above an if statement that will be executed each time the function is called. Below is the code I've put together for the purpose of this question:

let example x = 
    if (x == 1) then "Number is 1" 
    else if (even x) then example (x - 1) 
    else example (x - 2) 

What I want to happen is for the number to be printed each time the function is called, so logic was telling me to find out how to add a line above the if statement to print [x]. I've looked into it heavily but haven't been able to find a solution. I looked into the "Do" but I couldn't seem to get it working. If anyone can shine some light on this area it would be much appreciated.

Upvotes: 0

Views: 1684

Answers (3)

anubhav
anubhav

Reputation: 1

Have a look at the trace function. It does specifically what you are looking for. And the function's signature need not be changed.

import Debug.Trace

example x = trace ("Called with " ++ (show x)) $
    if (x == 1) then "Number is 1" 
    else if (even x) then example (x - 1) 
    else example (x - 2) 

Documentation for trace.

Upvotes: 0

bheklilr
bheklilr

Reputation: 54058

If you are going to print something to the screen, your function has to be an IO action, so to start with it needs a type signature indicating that. Next, to perform a series of IO actions inside your function, you should use the do syntax, but this means to return a value from it you need to use the return function:

example :: Int -> IO String
example x = do
    putStrLn $ "Calling: example " ++ show x
    if x == 1
        then return "Number is 1"
        else if even x
            then example (x - 1)
            else example (x - 2)

You don't need the return on example (x - 1) or example (x - 2) because the type of these expressions is IO String, it's already the type needed for the return value of this function. However, "Number is 1" just has type String. To turn it into IO String, you have to use the return function.

Upvotes: 1

Lee
Lee

Reputation: 144126

You need to return an IO () and you can use do notation e.g.

example :: Int -> IO ()
example x = do
  putStrLn $ "Number is " ++ (show x)
  case x of
    1 -> return ()
    _ -> if (even x) then example (x-1) else example(x-2)

Upvotes: 0

Related Questions