简体   繁体   中英

Haskell case statement

I have code something like this

main :: [[String]] -> IO ()
main st = do
    answer <- getLine
    case answer of
      "q" -> return ()
      "load" x -> main $ parseCSV $ readFile x

This doesn't work, so my question is how can I use case switch statement for something of changing input For example in my code I want the input from a user to be either q or a load, but the load will constant change:

load "sample.csv"
load "test.csv"
load "helloworld.csv"

In my code I indicated the constantly changing input as X, but this doesn't work as I expected it.

Help would be appreciated, thank you.

As others have mentioned, the problem is with your pattern matching.

Here's a simple way to get around this (and still have something readable).

  1. Split answer into words for matching (with the words function).
  2. Use the first word in the pattern match.
  3. If you want to use the remaining "words", simply unwords the remaining elems in the list to get a string.

Example:

main :: IO ()
main = do
    answer <- getLine
    case words answer of
        ("q":_)    -> putStrLn "I'm quitting!"
        ("load":x) -> putStrLn ("Now I will load " ++ unwords x)
        otherwise  -> putStrLn "Not sure what you want me to do!"

Note - the x you had above is actually unwords x here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM