Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert binary string to integer value using first order functions

Given a finite list of 0 and 1, how can I convert them to their integer value using first order function?

The head of the list is the least significant digit. For instance, 1011 evaluates to 13.

In this problem, I struggle to find both the recursive step and the base step because all depends wether it's a 0 and 1.

EDIT :

The goal is to define a function that will compute the decimal value given a binary string. An empty list should return 0 I guess, so it would be the base case.

like image 336
Pierre P. Avatar asked Jul 14 '26 22:07

Pierre P.


1 Answers

Wrapping up my comments:

convert :: [Int] -> Int
convert [] = 0
convert (x : xs) = x + 2 * convert xs

The base case is the empty list, returning 0.

The recursive case follows from the fact that x is the least significant digit. convert xs (the recursive call) gives us the result for the tail of the list; to get the result of the whole list we need to multiply by 2 (to "shift over" the digits) and add x (0 or 1).

like image 134
melpomene Avatar answered Jul 17 '26 20:07

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!