Haskell Bytestrings: How to pattern match?

前端 未结 5 600
悲&欢浪女
悲&欢浪女 2020-12-28 14:23

I\'m a Haskell newbie, and having a bit of trouble figuring out how to pattern match a ByteString. The [Char] version of my function looks like:

5条回答
  •  攒了一身酷
    2020-12-28 14:56

    Patterns use data constructors. http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html

    Your empty is just a binding for the first parameter, it could have been x and it would not change anything.

    You can't reference a normal function in your pattern so (x cons empty) is not legal. Note: I guess (cons x empty) is really what you meant but this is also illegal.

    ByteString is quite different from String. String is an alias of [Char], so it's a real list and the : operator can be used in patterns.

    ByteString is Data.ByteString.Internal.PS !(GHC.ForeignPtr.ForeignPtr GHC.Word.Word8) !Int !Int (i.e. a pointer to a native char* + offset + length). Since the data constructor of ByteString is hidden, you must use functions to access the data, not patterns.


    Here a solution (surely not the best one) to your UTF-16 filter problem using the text package:

    module Test where
    
    import Data.ByteString as BS
    import Data.Text as T
    import Data.Text.IO as TIO
    import Data.Text.Encoding
    
    removeAll :: Char -> Text -> Text
    removeAll c t =  T.filter (/= c) t
    
    main = do
      bytes <- BS.readFile "test.txt"
      TIO.putStr $ removeAll 'c' (decodeUtf16LE bytes)
    

提交回复
热议问题