Currently i have 2 methods: parse_int
and parse_string
. They return either one number or one string, respectively. For example, if i have the parser tuple((parse_int, parse_string))
, then it will convert " 123 sdf"
to (123, "sdf")
.
My actual parser looks like tuple((parse_string, opt(parse_int), opt(parse_string)))
. It will succesfully convert " dsf 123 sdf"
to ("dfs", Some(234), Some("sdf"))
, which is good. But if I enter "dfs sdf"
as input, then we get ("dfs", None, Some("sdf")))
. And I want it to return to me ("dfs", None, None))
, because sdf
could not be converted to int. For a better understanding, I am making a command args parser.
Asked
Active
Viewed 59 times
0

olegshmel
- 13
- 2
- 4
1 Answers
0
Use tuple()
inside opt()
, to tie parse_int
and parse_string
together:
tuple((parse_string, opt(tuple((parse_int, opt(parse_string))))))
It will produce (&str, Option<(int, Option<&str>)>)
instead of (&str, Option<int>, Option<&str>)
. You can use map()
to flatten it if desired.

Chayim Friedman
- 47,971
- 5
- 48
- 77
-
Not quite, this is what I thought but look carefully at their desired output for `"dfs sdf"`. – orlp Jun 26 '22 at 21:52
-
@orlp Are you saying because the double `None`? This is what I said you can flatten. – Chayim Friedman Jun 26 '22 at 21:55
-
No, I'm referring to the fact they only want `"dfs"` as the output in that scenario, stopping on the first whitespace. – orlp Jun 26 '22 at 21:56
-
@orlp They also split by whitespaces in the successful scenario - so I think their parsers stop on whitespaces. – Chayim Friedman Jun 26 '22 at 22:09
-
Not quite what I expected. What if i have 3 optional arguments, like this: `tuple((parse_string, opt(tuple((parse_string, opt(parse_int), opt(parse_string))))))`. This code will not correctly work for `" dfs sdf sdf"`. The only solution that came to mind is such a large parser `tuple((parse_string, opt(tuple((parse_string, opt(tuple((parse_int, opt(parse_string)))))))))` (it works). I think there are simpler options. – olegshmel Jun 27 '22 at 08:41
-
@olegshmel Indeed, nesting them is what I would do. You can create a helper parser combinator to do that, I don't think one exists in nom. – Chayim Friedman Jun 27 '22 at 09:22