1

I want to write a function f that converts a binary list to an integer, like:

f :: [Integer] -> Integer
f [] = 0
f list = (last list) * 2^(length list -1) + f (init list)

For example, in f [1,1,1,1,0,0,1,0] = 79, the first list element represents 2^0 and the last list element represents 2^7.

Can I write this function with higher-order functions instead of with explicit recursion?

6
  • 1
    Yes, you can do this with foldl. Commented Dec 1, 2020 at 13:20
  • Thats what i thought, but how i can handle (length list -1) in foldl ? Commented Dec 1, 2020 at 13:45
  • 1
    Forget about exponentiation and length. Think abcd = 1*d + 2*c + 2*2*b + 2*2*2*a = 1*d + 2*(c + 2*(b + 2*a))). Commented Dec 1, 2020 at 13:47
  • 1
    @Sambud_Ger: you don't need the length, if you each time multiply with two, and add the value, eventually you obtain 2^n. Commented Dec 1, 2020 at 13:47
  • molbdnilo refers to Horner's method. Commented Dec 1, 2020 at 14:14

2 Answers 2

1

It appears the order of your list is unfortunate for foldl, but you can pass the exponent along like so:

intvalueOfList = fst . foldl f (0,1) 
   where f (acc,exp) e = (acc+e*exp, exp*2)
Sign up to request clarification or add additional context in comments.

Comments

1

You can make use of foldr :: Foldable f => (a -> b -> b) -> b -> f a -> b which uses a "folding" function that takes an element and the accumulator. The accumulator conceptually runs right-to-left over the list. You can thus each time souble the accumulator and then add the value of the element:

f :: (Foldable f, Num a) => f a -> a
f = foldr g 0
    where g x acc = …

where you still need to fill in g.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.