Good Haskell coding style of if/else control block?

后端 未结 8 1548
慢半拍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: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?

提交回复
热议问题