chunksOf和string数据类型

时间:2017-03-13 08:54:14

标签: 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 . chunksOf 2 . show

编码有效,但在decodInts,我得到了:

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

* 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 #-}

2 个答案:

答案 0 :(得分:3)

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

chunksOf 2 :: Text -> [Text]

使用chunksOf中的Data.List.Split或自己编写:

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

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

答案 1 :(得分:1)

如果您的字符串中只有ASCII(或至少没有unicode)且没有零Char,则可以使用此

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)