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

尝试将字节串转换为十六进制 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)。

https://stackoverflow.com/questions/7693670/

相关文章:

vim - 你如何在 Vim 中删除除特定模式之外的所有内容?

ruby-on-rails - Rspec测试,关于顺序和之前(:all)

django - 更改各种对象的 django-tinymce 内容 css

wpf - 自动将文本框中的第一个字母大写

haskell - 在 Haskell 中打印元组内的值

performance - @font-face unicode-range 属性

opengl - 可在 OpenGL 中表示的曲线

asp.net - Rad Ajax 加载面板未显示在 asp.net 页面的回发中

css - 如何并排显示两个高度为 100% 的 Div?

php - 使用 facebook sharer.php 与多个 url 变量共享一个 url