How can I use elm/parser to make a Float from a String?

I have a string that looks like this 4.6.178.3429
Can someone explain how I would use elm/parser to turn this into a float that looks like this 4.6?

Essentially, your code should look something like this:

test : String -> Maybe Float
test string = 
    string
    |> Parser.run Parser.float
    |> Result.toMaybe

Here are some results:

"4.6.178.3429" -> Just 4.6
"4.6test.178.3429" -> Just 4.6
"4test.6.178.3429" -> Just 4
"test4.6.178.3429" -> Nothing

Checkout the talk Demystifying Parsers by Tereza Sokol for a detailed explanation of elm/parser.
I you don’t want to watch the full video, checkout this summary.

2 Likes

So I just realized this solution is not going to work. I’m trying to parse a version number so 4.100 is greater than 4.1, but of course a float does not care about trailing zeros so 4.100 turns into 4.1. My attempt at writing my own parser to handle each part (major, minor, patch, millipatch) has ended in failure.

I think I need some combination of chompWhile Char.isDigit, getChompedString, some way of turning that chomped string into an int, throwing out the “.”, and doing it all again, but how to accomplish that isn’t clear to me.

Would you mind helping me out some more? I have an Ellie happening: https://ellie-app.com/5L3vY6QCq4ka1

Sure.
But I’m not quite sure what you actually try to archive.
Could you maybe give me some inputs and the expected output?

Your ellie looks fine to me, only the Result.withDefault confuses me -> whats the problem with Result.toMaybe?

Edit:
Just realized that your ellie does wierd things. Let me see if i can fix it.

This should work:

https://ellie-app.com/5L5WB9qcsJ9a1

1 Like

Thanks for the help!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.