【问题标题】:decimal integer to Base4 string Haskell十进制整数到 Base4 字符串 Haskell
【发布时间】:2021-04-20 12:10:13
【问题描述】:

我正在尝试将整数从十进制整数转换为基于 4 的字符串,但我的展开器不起作用,我不确定为什么或如何替换它。我也不能使用进口。请帮我解决这个问题。

dec2Base4 :: Int -> String
dec2Base4 = map i2c . reverse . unfoldr decomp
    where
    decomp n = if n == 0 then Nothing else Just(n `mod` 4, n `div` 4)
    i2c i = if i == 0 then '0' else if i == 1 then '1' else if i == 2 then '2' else '3'

例如:dec2Base4 10-> "22"

【问题讨论】:

  • 为我工作。你怎么了?
  • $ghc -O2 --make *.hs -o main -threaded -rtsopts [1 of 1] Compiling Main ( main.hs, main.o ) main.hs:46:33: error: • Variable not in scope: unfoldr :: (Integer -> Maybe (Integer, Integer)) -> Int -> [Integer] • Perhaps you meant ‘foldr’ (imported from Prelude)
  • 你可以使用iterate吗? scanl? unfoldr 可以同时实现(或直接递归)。 scanl 可以按照zip and map 来实现...
  • 元:如果您有多个帐户,您可以要求版主将这些帐户合并为一个。 (我不确定确切的程序)。
  • 您可以从通过递归获得的辅助字符串开始:let { auxStr 0 = "" ; auxStr n = let (q,r) = divMod n 4 in (i2c r) : (auxStr q) }

标签: haskell base


【解决方案1】:

你的代码基本没问题,但是需要你从Data.List包中导入unfoldr函数。

您被禁止使用import 子句这一事实可能只是意味着权力希望您使用普通递归。

基于递归的解决方案:

不幸的是,递归自然会首先产生最低有效位(最右边的数字),因为这个最右边的数字本质上是mod n 4。您必须使用 reverse 函数来纠正它,就像在基于库的代码中一样。

例如,在没有任何非 Prelude 库函数的帮助下,dec2Base4 函数可以这样写:

dec2Base4 :: Int -> String
dec2Base4 n
    |  (n < 0)    =  '-' : (reverse (auxStr (-n)))
    |  (n == 0)   =  "0"
    |  otherwise  =  reverse (auxStr n)  -- when n > 0
  where
    i2c i     =  "0123" !! i
    auxStr 0  =  ""
    auxStr n  =  let  (q,r) = (divMod n 4)  in  (i2c r) : (auxStr q)

测试代码:

unitTest :: Int -> IO ()
unitTest n = do
    let res = dec2Base4 n
    putStrLn $ "Result for " ++ (show n) ++ " is: " ++ res

main = do
    let  testList = [0,11,2051,-2051]
    mapM_  unitTest  testList

测试程序输出:

Result for 0 is: 0
Result for 11 is: 23
Result for 2051 is: 200003
Result for -2051 is: -200003

【讨论】:

  • 使用尾递归,无需反转。考虑auxStr n acc = let (q,r) = (divMod n 4) in auxStr q (i2c r : acc)。 :)
猜你喜欢
  • 2017-08-07
  • 1970-01-01
  • 2021-06-29
  • 2013-10-22
  • 1970-01-01
  • 2018-03-21
  • 2013-04-28
  • 2013-02-02
  • 2014-03-07
相关资源
最近更新 更多