Haskell chunksOf和string数据类型

Haskell chunksOf和string数据类型,haskell,Haskell,我需要一个函数来将控制台中类似“Hello World”的字符串转换为整数,然后将整数转换回字符串 import Data.Text (Text, chunksOf) encodeInts :: String -> Integer encodeInts = read . concatMap show . map ord . show decodeInts :: Integer -> String decodeInts = read . map chr . map read . ch

我需要一个函数来将控制台中类似“Hello World”的字符串转换为整数,然后将整数转换回字符串

import Data.Text (Text, chunksOf)

encodeInts :: String -> Integer
encodeInts = read . concatMap show . map ord . show
decodeInts :: Integer -> String
decodeInts = read . map chr . map read . chunksOf 2 . show
编码是有效的,在
decodins
中,但是,我得到:

* Couldn't match type `[Char]' with `Text'
  Expected type: Integer -> Text
    Actual type: Integer -> String
* In the second argument of `(.)', namely `show'
  In the second argument of `(.)', namely `chunksOf 2 . show'
  In the second argument of `(.)', namely
    `map read . chunksOf 2 . show' Failed, modules loaded: none. Prelude>

我已经尝试过使用
{-#LANGUAGE OverloadedStrings}

您会收到该错误,因为
chunksOf
的类型错误:

chunksOf 2 :: Text -> [Text]
使用
Data.List.Split中的
chunksOf
,或者编写自己的:

chunksOf :: Int -> [a] -> [a]
chunksOf _ [] = []
chunksOf k xs = let (as, bs) = splitAt k xs 
                in as : chunksOf k bs
也就是说,你的功能不起作用
ord'o'
111
,一个三位数字。我会写更简单的变体:

encodeInts :: String -> [Int]
encodeInts = map ord

decodeInts :: [Int] -> String
decodeInts = map chr

毕竟,从
Integer
获取
[Int]
的过程是模棱两可的,即使长度是固定的,因为第一个字符的
ord
可能小于100。

之所以会出现此错误,是因为
chunksOf
的类型错误:

chunksOf 2 :: Text -> [Text]
使用
Data.List.Split中的
chunksOf
,或者编写自己的:

chunksOf :: Int -> [a] -> [a]
chunksOf _ [] = []
chunksOf k xs = let (as, bs) = splitAt k xs 
                in as : chunksOf k bs
也就是说,你的功能不起作用
ord'o'
111
,一个三位数字。我会写更简单的变体:

encodeInts :: String -> [Int]
encodeInts = map ord

decodeInts :: [Int] -> String
decodeInts = map chr
毕竟,从
Integer
获取
[Int]
的过程是模棱两可的,即使长度固定,因为第一个字符的
ord
可能小于100。

如果字符串中只有ASCII码(或至少没有unicode码)并且没有零
字符,那么您可以使用这个

encodeInts :: String -> Integer
encodeInts = foldr (\c n -> n * 256 + toInteger (ord c)) 0
decodeInts :: Integer -> String
decodeInts = map (chr . fromInteger) $ takeWhile (> 0) $ map (`mod` 256) $ iterate (`div` 256)
如果您的字符串中只有ASCII码(或者至少没有unicode码),并且没有零
Char
s,那么您可以使用

encodeInts :: String -> Integer
encodeInts = foldr (\c n -> n * 256 + toInteger (ord c)) 0
decodeInts :: Integer -> String
decodeInts = map (chr . fromInteger) $ takeWhile (> 0) $ map (`mod` 256) $ iterate (`div` 256)

我很困惑-只是
show
read
有什么不对?很抱歉没有提及:我需要将
Hello
这样的字符串转换为整数表示形式,而不仅仅是像'123'这样的字符串,你用的是
chunksOf
吗?@Zeta我用的是数据中的
chunksOf
。text好吧,这是你的问题。
文本
不是
字符串
。我很困惑-只是
显示
读取
有什么问题?很抱歉没有提及:我需要将字符串(如
Hello
转换为整数表示形式,不仅仅是像'123'这样的字符串,你使用哪个
chunksOf
呢?@Zeta我使用的是Data.text中的
chunksOf
文本
不是
字符串