2

im new to Haskell and dont understand how haskell handles recursion. Ive been working on this for months and just cant figure it out. My project is due in a few days, so im asking for any help or advice! My project description is to have 7 "criminals" with three of them are "guilty" i have to randomly display three of 7 criminals, tell how many of the three are guilty, and ask if the user want to make a guess at whos guilty or pass until all have been guessed correctly. I have figured out most of everything else, im just stuck on how to use a recursive function to repeatedly display 3 randoms from the 7, ask for input, and check if its right.

Ok so from looking at the stuff you've gave me, i tried to make a small function to try to practice using recursion as a loop before i implement it into my project, this is what i came up with:

main = do
    num <- 7
    print recursion(num)


let recursion a = do
    putStrLn "guess my number!" 
    guess <- getLine 

    if a==guess 
        then print "good job"
            return guess
        else
            recursion a

but im getting some parse errors on the lines towards the end, could you tell me what im doing wrong? @stonemetal

1
  • 3
    What code do you have so far? Stackoverflow is a community to ask for help, not to ask for code. Commented Nov 21, 2013 at 16:57

1 Answer 1

1

The recursive function should be the easy part. All you need to do is decide when to end the recursion then call the function again if that condition is not true.

let runGame gameData = do newGameData <- runOneIterationOfGame gameData
                          if gameOver newGameData then
                            return newGameData
                          else
                            runGame newGameData
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help so far!..... but im looking for more of an explanation, do you mind describing that function in a little detail? Like i said im new too this and dont have a good understanding of it
@kpholsey gamedata should hold all of the state, which prisoners are guilty, what the user has guessed etc. runOneIterationOfGame displays info about the random 3, takes the players input etc. gameOver is a function that returns true if the user guessed correctly. If the user guessed correctly then we can exit the game, if the user didn't guess correctly then you need to run another iteration of the game you do that by calling runGame with the updated state. Whenever you write a recursive function look for two things, the end of recursion and what gets you a step closer to it.

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.