0

Haskell and functional programming is something I am not familiar with, and this semester I got to meet Haskell for the very 1st time. I got unlimited loop when I tried to do a recursion (not very proud of it)

Here's the code

import Data.List
import System.IO

mrLoop :: Int -> Int -> IO()
mrLoop a b = do
    if b == 10 then return ()
    else
        print(a*b)
    mrLoop a (b+1)


main = do mrLoop 2 0

So I tried to play with it and somehow it works

mrLoop :: Int -> Int -> IO()
mrLoop a 10 = return()
mrLoop a b = do
    print(a*b)
    mrLoop a (b+1)

But a friend of mine says that's not the Haskell way. So how do I do it in an Haskell way? And why the 1st code doesn't work?

1 Answer 1

5

The first version recurses forever because the mrLoop a (b+1) action is outside the if/else expression.

In other words, it either does nothing or prints a*b, and then it unconditionally recurses into mrLoop a (b+1). It'll keep recursing forever.

In the latter example, recursion stops when the pattern-matched function hits the base case where b is 10.

Your friend probably means that this isn't the Haskell way because the Haskell way is to separate pure functions from impure actions.

Try if you can write the recursive 'loop' as a pure function (i.e. without IO). What would it return? How could you then use that return value to print a series of results?

Sign up to request clarification or add additional context in comments.

7 Comments

It's probably worth mentioning explicitly that return does not cause the function call to exit, a common misconception with beginners to Haskell.
so basically, do the recursion on the main function?
@FARHANDIKAZAHRIRMUFTIGUENIA I'm not sure what you mean, but that doesn't sound right. As my answer implies, you can write recursive pure functions. Most introductions to Haskell will tell you how early in the materials.
i still dont get it, is it possible for you to show me an example on how to do the loop the haskell way?
@FARHANDIKAZAHRIRMUFTIGUENIA I could, but I don't think your school would appreciate it if you don't do your exercises yourself.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.