I've been looking to write a lexer in Haskell and stumbled upon these functions.
If defined,
some
andmany
should be the least solutions of the equations:
some v = (:) <$> v <*> many v
many v = some v <|> pure []
I get that the (:)
in some
gets lifted and applied to the value of v
in order to prepend it to the list returned in many v
.
But why does the definition of many
start with some
? And why does it get concatenated with pure []
?
What is the relationship or difference between these two functions? What does it mean for some
and many
to be the least solutions of those equations? And how does the recursion ever stop? Help!
some p
means one or more match of pmany p
means zero or more more match of pFor input
"abc"
,many letter
andsome letter
will both parseabc
.But for input
"123"
,many letter
will output empty string""
.some letter
will report error.According to the definition.
some v
needs at least 1 match ofv
, so we can first parsev
then we need 0 or more match ofv
, which ismany v
. It is something like :which is the same as
some v = (:) <$> v <*> many v
.But for
many v
. It will either matchsome v
(1 or more) or nothing (pure []).many v = if matches (some v) then return (some v) else return nothing
.You can try solve writing applicative parsers from scratch from codewars.
Functional pearls is also a very good reference about parse combinators.