Drkcore

07 07 2012 Haskell Tweet

Invent With PythonのGuess the NumberをHaskellで

Guess the NumberをHaskellで

import System.Random

randomNumGen :: IO Int
randomNumGen = getStdRandom (randomR (1,20))

main :: IO ()
main = do
  print "Hello! What is your name?"
  myName <- getLine
  print $ "Well, " ++ myName ++ ", I am thinking of a number between 1 and 20."
  print "Take a guess."
  answer <- randomNumGen
  guessNumber 0 answer myName
      where guessNumber gt answer name =
              if gt > 4 
              then do print $ "Nope. The number I was thinking of was " ++ show answer
              else do
                  line <- getLine
                  let guess = read line :: Int
                  case (compare guess answer) of
                    LT -> print "Your guess is too low." >> guessNumber (gt + 1) answer name
                    GT -> print "Your guess is too high." >> guessNumber (gt + 1) answer name
                    EQ -> print $ "Good job, " ++ name ++ "! You guessed my number in " ++ (show gt) ++ " guesses!"

ユーザーからの入力を読み込んでIntに直すときに

line <- getLine
let guess = read line :: Int

ってやったけど、本当はどうやるのがいいんだろうか?

それから、名前と答えを関数で持ちまわるのがダサいが、こういう場合ReaderTとStateTどっち使うべきなんだろうか?

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021