xsx
xsx

Reputation: 171

how do I accept user inputs and call functions based on the them?

import System.IO

makeGrid :: Int -> Int -> a -> [[a]]
makeGrid x y = replicate y . replicate x

startGame = do
putStrLn "Select a difficulty (1,2): "
difficulty <- getLine
|difficulty == '1' = makeGrid 3 3 False
|difficulty == '2' = makeGrid 5 5 False
|otherwise = putStrln "Wrong thing"
             some function            --start from beginning again

As you see, I have a function makeGrid. I want to take user input in startGame and call makeGrid based on the user input. Also do a while loop if possible, how should I do that?

Upvotes: 0

Views: 224

Answers (1)

Gurkenglas
Gurkenglas

Reputation: 2317

{-# LANGUAGE LambdaCase #-}

import System.IO

playGame = do
  grid <- initializeGrid
  -- game code goes here

initializeGrid = do
  putStrLn "Select a difficulty (1,2): "
  getLine >>= \case -- "difficulty <- getLine" <newline> "case difficulty of" also ok
    "1" -> return $ makeGrid 3 3 False
    "2" -> return $ makeGrid 5 5 False
    _   -> do
      putStrln "Wrong thing"
      initializeGrid

makeGrid :: Int -> Int -> a -> [[a]]
makeGrid x y = replicate y . replicate x

Upvotes: 3

Related Questions