Good Haskell coding style of if/else control block?

后端 未结 8 1544
慢半拍i
慢半拍i 2021-01-31 09:15

I\'m learning Haskell in the hope that it will help me get closer to functional programming. Previously, I\'ve mostly used languages with C-like syntax, like C, Java, and D.

相关标签:
8条回答
  • 2021-01-31 09:53

    You can use the "case"-construct:

    doGuessing num = do
        putStrLn "Enter your guess:"
        guess <- getLine
        case (read guess) of
            g | g < num -> do 
                putStrLn "Too low!"
                doGuessing num
            g | g > num -> do 
                putStrLn "Too high!"
                doGuessing num
            otherwise -> do 
                putStrLn "You Win!"
    
    0 讨论(0)
  • 2021-01-31 09:54

    A minor improvement to mattiast's case statement (I'd edit, but I lack the karma) is to use the compare function, which returns one of three values, LT, GT, or EQ:

    doGuessing num = do
       putStrLn "Enter your guess:"
       guess <- getLine
       case (read guess) `compare` num of
         LT -> do putStrLn "Too low!"
                  doGuessing num
         GT -> do putStrLn "Too high!"
                  doGuessing num
         EQ -> putStrLn "You Win!"
    

    I really like these Haskell questions, and I'd encourage others to post more. Often you feel like there's got to be a better way to express what you're thinking, but Haskell is initially so foreign that nothing will come to mind.

    Bonus question for the Haskell journyman: what's the type of doGuessing?

    0 讨论(0)
提交回复
热议问题