gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:24:55 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com