2

I need to write a function with the following type

replaceSubtrie :: SSTrie -> Data.Word.Word8 -> SSTrie -> SSTrie
replaceSubtrie trie base subtrie = ???

where depending on the value of base, the subtrie will be inserted into the trie in differing ways. SSTrie is my own data type and I know how to work with it, but I have no idea how to deal with the Word8 value.

base is a single "character" (for certain values of "character") taken from a ByteString. Specifically, it is the result of calling index on ByteString -- that's the only reason why I've declared it Word8.

I can't do pattern matching, as there's no Word8 constructor available. And I can't get guards to work because I don't know how to construct a Word8 constant to compare it against.


[edited] Jerome's suggestiong worked. But more generally, are there any good articles out there showing how to work with Bytestrings (and other more low-level data)? Like, how could I have known that fact about Word8?


[edited - Question for Don Stewart]

Right now I've got it working with code like this

replaceSubtrie trie 0x41 subtrie = trie{ a=subtrie }

When I change it to this:

replaceSubtrie trie 'A' subtrie = trie{ a=subtrie }

I get an error:

Trie.hs:40:21:
Couldn't match expected type `Word8' with actual type `Char'
In the pattern: 'A'
In an equation for `replaceSubtrie':
    replaceSubtrie trie 'A' subtrie = trie {a = subtrie}

I do have import qualified Data.ByteString.Char8 as C at the top of my file. What am I doing wrong?

JonathanZ
  • 1,046
  • 11
  • 20
  • 2
    Word8 is an unsigned 8-bit value. It also is Num, Bounded, Eq, Ord...etc so you can consider it 0 to 255 (http://hackage.haskell.org/packages/archive/base/4.6.0.0/doc/html/Data-Word.html) so you should be able to use patterm match. – Jerome Nov 19 '12 at 05:13
  • Thanks, Jerome, that worked. I feel a bit silly looking up the ASCII value for 'A', but what the hell. – JonathanZ Nov 19 '12 at 05:18
  • Also read http://www.haskell.org/haskellwiki/DealingWithBinaryData. – Björn Lindqvist Nov 19 '12 at 08:33

1 Answers1

1

I feel a bit silly looking up the ASCII value for 'A', but what the hell

You can simply import Data.ByteString.Char8 or Data.ByteString.Lazy.Char8, to get all the same functions, but permitting the use of character literals in patterns.

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
  • You can do this, but if you do it's probably a smell that something is wrong. `Char8` is dangerous – singpolyma Nov 19 '12 at 15:32
  • 1
    It should only be used as a convenience accessor for binary data. That's why I wrote it. – Don Stewart Nov 19 '12 at 16:10
  • Could you clarify that? I've added details of what I'm doing to the top question (I'm not quite sure of how stackexchange likes to structure conversations.) – JonathanZ Nov 19 '12 at 23:55