简体   繁体   中英

Haskell List to Tuple

I am writing a function, parseArgs , which will take in command line arguments in the form of a list. If the size of the list is two, the function is to parse the contents of the list and convert them to a tuple, otherwise returning Nothing . I am unsure of quite how to go about this; my code thus far is below:

parseArgs :: [String] -> Maybe (String, Maybe String)
parseArgs [x, y]
  | length [x, y] < 2 = Nothing
  | length [x, y] > 2 = Nothing
  | otherwise = Just (x, Just y)

In your code, parseArgs [x, y] means it only accepts exactly a list of two elements. So length [x, y] will always be 2, and those (>2) (<2) conditions will never be met.

otherwise will always be a list of two elements. So when the input is a list of two elements, you can get x and y, and make them a Maybe tuple for sure.

But other than that, if you parseArgs [] parseArgs ["a"] parseArgs ["a","b","c"] , you get an exception "Non-exhaustive patterns in function parseArgs". It is because the code didn't cover all the patterns in [String]

I use Maybe (String, String) for output here. It means parseArg will either produce Just (String, String) or Nothing. Perhaps it's closer to what you want.

So try this:

parseArgs :: [String] -> Maybe (String, String)
parseArgs x:y:[] = Just (x,y)
parseArgs xs = Nothing

It means if the input [String] happens to be x:y:[] (a list of exact two strings), produce Just (x,y). Other than that, produce Nothing. In this way, it covers all patterns in [String]. And you then can get Nothing when it is not a list of two elements.

Edit: And second to @pdoherty926's parseArgs _ = Nothing , the wildcard _ is a better way to express "everything else".

@Johhny Liao beat me to it, but here's my similar answer:

Based on your requirements, I'm unclear as to why the second tuple element would be Maybe String . So, I'm going to proceed as though the type of your function is: parseArgs :: [String] -> Maybe (String, String)

parseArgs :: [String] -> Maybe (String, String)
parseArgs [x, xx] = Just (x, xx)  -- pattern match on the list of two elements
parseArgs _ = Nothing               -- discard _everything_ else

print $ parseArgs ["hi", "bye"]    -- Just ("hi", "bye")
print $ parseArgs ["hi"]               -- Nothing

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