logoalt Hacker News

codebje11/08/20242 repliesview on HN

    data Color = Color
        { r :: Word8
        , b :: Word8
        , c :: Word8
        } deriving Show

    hex_primary :: Parser Word8
    hex_primary = toWord8 <$> sat isHexDigit <*> sat isHexDigit
        where toWord8 a b = read ['0', 'x', a, b]

    hex_color :: Parser Color
    hex_color = do
        _ <- char '#'
        Color <$> hex_primary <*> hex_primary <*> hex_primary
Sure, it works in Rust, but it's a pretty far cry from being as simple or legible - there's a lot of extra boilerplate in the Rust.

Replies

jeroenhd11/08/2024

I think it's a stretch to call parser combinator code in Haskell simple or legible. Most Haskell code is simple and legible if you know enough Haskell to read it, but Haskell isn't exactly a simple or legible language.

Haskell demonstrates the use of parser combinators very well, but I'd still use parser combinators in another language. Parser combinators are implemented in plenty of languages, including Rust, and actually doing anything with the parsed output becomes a lot easier once you leave the Haskell domain.

show 2 replies
orf11/08/2024

The nom crate has an RGB parser example: https://docs.rs/nom/latest/nom/#example

It’s slightly longer, but more legible.

show 1 reply