在将其作为参数传递之前反转List

时间:2016-02-06 06:18:07

标签: algorithm list haskell

我在Haskell上相当新,而且我现在一直试图解决一段时间的解决方案,但我似乎无处可去。

我已经定义了一个名为Binary递归的数据类型

data Binary = BaseOne | Zero Binary | One Binary

我试图创建一个以列表形式获取二进制数的函数(即[1,1,0,1]并将其转换为我的数据类型Binary。

binListaBin :: [Int] -> Binary
binListaBin []              = error "Empty List."
binListaBin [1]             = BaseOne
binListaBin x:xs
            | x == 0    = Zero (binListaBin xs)
            | x == 1    = One  (binListaBin xs)
            | otherwise = error "Not a binary."

问题是我的函数反转结果,所以我的猜测是如果我可以在函数使用它之前反转输入列表,它应该正常工作,但我不知道如何做到这一点在功能里面。我试过用 句子来解决这些问题,但似乎无法做到正确。

2 个答案:

答案 0 :(得分:2)

在通过创建别名函数将列表传递到binListaBin函数之前,将其反转。

binListaBin xs = binListaBinInner $ reverse xs

binListaBinInner :: [Int] -> Binary
binListaBinInner []              = error "Empty List."
binListaBinInner [0]             = BaseOne
binListaBinInner [1]             = BaseOne
binListaBinInner x:xs
            | x == 0    = Zero (binListaBinInner xs)
            | x == 1    = One  (binListaBinInner xs)
            | otherwise = error "Not a binary."

答案 1 :(得分:1)

这就是我要做的事情:

import Data.List (foldl') -- strict foldl

data Binary = BaseOne     -- The leading one in front of all binary numbers
            | Zero Binary -- Zero followed by a string of binary digits
            | One Binary  -- One followed by a string of binary digits
            deriving Show

toBinary :: Int -> Binary -> Binary
toBinary 0 = Zero
toBinary 1 = One

flipToBinary :: Binary -> Int -> Binary
flipToBinary = flip toBinary

foldBinary :: [Int] -> Binary
foldBinary (1:xs) = foldl' flipToBinary BaseOne xs

让我们看一个例子。我们将使用我最喜欢的二进制数字11表示为[Int]

  8 + 0 + 2 + 1 = 11

[ 1 , 0 , 1 , 1 ]

foldBinary函数将其转换为Binary表示形式:

foldBinary [1,0,1,1] = One (One (Zero BaseOne))

Binary中,它表示为One (One (Zero BaseOne))。向后是向前。