Hacker News new | ask | show | jobs
by bkirwi 4131 days ago
Here you go, then:

    -- little-endian sequence of bytes to arbitrary integral type
    integerWithBytes :: (Bits a, Integral a) => [Word8] -> a
    integerWithBytes = foldr (\byte acc -> (acc `shiftL` 8) + fromIntegral byte) 0
At least, I'm pretty sure that's what the article was trying to do...

I don't think this is some amazing showcase of Haskell; after all, the article includes a (working?) implementation in C++. But it does serve as a nice counterexample to the idea -- expressed elsewhere in the thread -- that being generic is necessarily a hugely painful or complicated thing.

1 comments

Yep this works:

    λ> import Data.Bits
    λ> let integerWithBytes = foldr (\byte acc -> (acc `shiftL` 8) + fromIntegral byte) 0
    λ> integerWithBytes [0xFF, 0xFF, 0xFF, 0xFF]
    4294967295