haskell - 与 Word8 和 Int 相关的类型错误

标签 haskell

尝试将字节串转换为十六进制 ascii 字符串显示

wordtoascii :: Int -> String
wordtoascii y =
  showIntAtBase 16 intToDigit ( fromEnum  y) ""

bs2string :: Data.ByteString.ByteString -> String
bs2string bs = do
  Prelude.map( wordtoascii,
               (unpack bs))

类型错误:

Couldn't match expected type `a -> b'
       against inferred type `(Int -> String, [GHC.Word.Word8])'
In the first argument of `Prelude.map', namely
    `(wordtoascii, (unpack bs))'
In the expression: Prelude.map (wordtoascii, (unpack bs))
In the expression: do { Prelude.map (wordtoascii, (unpack bs)) }

最佳答案

这不是您认为的语法。

Prelude.map( wordtoascii,
            (unpack bs))

这等同于:

let x = (wordtoascii, unpack bs)
in map x

删除括号和逗号。

map wordtoascii (unpack bs)

但是,这也是错误的。因为上面表达式的类型是[String],而不是String。您需要 concatMap,它类似于 map,但将结果拼接在一个字符串中。

concatMap wordtoascii (unpack bs)

或者,甚至更好,

bs2string = concatMap wordtoascii . unpack

逗号用于创建元组、列表和记录。例如,(1, 7)::(Int, Int) 可以是笛卡尔坐标。逗号不会出现在函数调用中。

通常,ByteString 仅作为限定导入导入,因为许多函数与 Prelude 冲突。这消除了 Prelude. 对发生冲突的函数进行限定的需要。

import qualified Data.ByteString as S
bs2string = map wordtoascii . S.unpack

S 代表严格BS也是一个常见的选择,它代表Bytestring (Strict)。

关于haskell - 与 Word8 和 Int 相关的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7693670/

相关文章:

haskell - 使 (a, a) 成为仿函数

python - Thrift 服务器对于简单操作来说确实很慢

haskell - 在 Haskell 中播放声音样本的最简单方法是什么?

haskell - 愚蠢的重复记录字段错误

haskell : "Reading"字节串

Excel Automation with Haskell 出现段错误

Haskell 类型类(Float 并不意味着 Floating?)

python - 如何在 Haskell 中使用 Data.MessagePack

haskell - 不知道为什么这个模式守卫匹配

haskell - parsec 如何递归解析简单表达式?