How do I create a menu for navigating to another file in Haskell

196 views Asked by At

I have three files (Play.hs, Sudoku.hs and Nim.hs), and each one of those files has a main.

I want to make a main in Play.hs to run one of those games (either Nim or Sudoku), like this:

main :: IO ()
main = do
          putStrLn "1-Sudoku"
          putStrLn "2-Nim"
          putStrLn "choice----->"
          let x=getLine
          if x==1 then
              ....
          else 
              ...
2

There are 2 answers

6
Daniel Wagner On

You may call the main value from other modules just fine, as long as add the line module Nim where to the top of Nim.hs, and similarly for Sudoku.hs.

Of course, if you have more than one main in scope, there will be ambiguity; but you can deal with ambiguity in the same way for main as you do for other names by qualifying them.

import Sudoku
import Nim

main = do
    ...
    if x == 1 then Sudoku.main else Nim.main

..and if you're in the interpreter, start your program with Play.main.

0
Bartek Banachewicz On

You can use import qualified to resolve the ambiguity and simply call respective main from the game you need.

Make sure you've started Sudoku.hs with

module Sudoku where

and the same for Nim.hs; then you can do

import qualified Sudoku as S
import qualified Nim as N

main = 
    -- ....
    if x==1 then
        S.main
    else
        N.main