Iβm new to Julia and looking for a good way / advice on passing functions as arguments and keeping the types. My searches did not yield anything that seemed applicable, or at least I understood to be applicable.
As a sample project below I use parser combinators. Here we have two functions match
and repeat
that yield a parser than transforms a string into a (remainder :: String, result :: SomeType)
.
The function match
returns Char
, so I would like repeat( match('z') )
to return Vector{Char}
. How can I accomplish this? Keep in mind, I want to reuse repeat
to other parsers that might yield a totally different type.
Some options I thought of:
- Add a parameter to repeat to denote the input and output result type β ugly
- Annotate the signature of the function β canβt do this in Julia I think
Any insight would be appreciated
function match(c :: Char)
function charParser(s :: String) :: Tuple{String, Char}
if s[1] == c
return (s[2:end], c)
else
throw(ErrorException("Expected a specific charater"))
end
end
return charParser
end
function repeat(parser)
function repeatParser(s :: String) :: Tuple{String, Vector{Any}}
resultList = Vector{}()
try
while true
(s, result) = parser(s)
push!(resultList, result)
end
catch e
end
return (s, resultList)
end
return repeatParser
end
input = "zzz"
parser = repeat( match('z') )
println(
parser(input)
)
Output:
("", Any['z', 'z', 'z'])