3 ms·
That's the inverse of the function the author wants, which ought to have type '[Word8] -> Maybe a' (where 'Nothing' is returned when the bytes exceed the range
by panic 12y ago
That's the inverse of the function the author wants, which ought to have type '[Word8] -> Maybe a' (where 'Nothing' is returned when the bytes exceed the range of the type in question).
- tel 12y agoYou could use the Bits instance of Integer and then convert from Integer to your final type. All types instantiating Num support `fromInteger :: Num a => Integer -> a`. Unfortunately, the design of this interface was for syntactic convenience instead of semantic strength so it is silent on what happens when you project an infinite type like Integer into a finite one like Word8. Implementers might wrap the conversion or fail with some kind of exception. A better (if less convenient) implementation would end in a Maybe type.
- Filligree 12y agoMy bad. Then I'll leave it as an exercise for the reader; the signature of the correct function is the same.
- poikniok 12y agoThis is so typical in the Haskell world, comment with a short snippet of code that does not produce the intended result, and when this is pointed out dismiss it as a trivial implementation problem.
- bkirwi 12y agoHere 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.
- codygman 12y agoYep this works: λ> import Data.Bits λ> let integerWithBytes = foldr (\byte acc -> (acc `shiftL` 8) + fromIntegral byte) 0 λ> integerWithBytes [0xFF, 0xFF, 0xFF, 0xFF] 4294967295
- codygman 12y agoI feel like you are overstating both how much this happens in Haskell and how exclusive it is to the Haskell community. Also see bkirwi's response for the working version, then my reply to him for a sample run.