Moving a list before passing it as an argument

I'm new to Haskell, and now I'm trying to solve some kind of solution, but it seems like I can't find anything.

I defined a data type called binary recursively

data Binary = BaseOne | Zero Binary | One Binary

And I'm trying to make a function that takes a binary number in the form of a list (ie [1, 1, 0, 1] and converts it to my Binary data type.

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."

The problem is that my function returns a result, so I assume that if I can change the input list before the function works with it, it should work correctly, but I do not know how to do this inside the function. I tried to combine with the offers and offer the offers, but it seems that there can be no rights.

+4
2

, :

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)). .

+1

, 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."
+2

Source: https://habr.com/ru/post/1627544/


All Articles