Reputation: 1065
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.
Upvotes: 3
Views: 3335
Reputation: 1
Just double the acc and add it to the new element of the list . Easily use digitToInt to get the right list from the string _ st here . and foldl' for efficiency. This is Sanaz's answer
fromBin st = foldl' (\x acc -> x * 2 + acc ) 0 (map (digitToInt) st)
Upvotes: 0
Reputation: 85757
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).
Upvotes: 3
Reputation: 3041
Assuming the input is a list of 1
s and 0
s.
bin2num :: [Int] -> Int
bin2num list = go list 0
where go [] _ = 0
go (x:xs) n = (x*(2^n)) + (go xs (n+1))
Upvotes: 0
Reputation: 1182
Here's my initial thoughts about how to handle this situation.
import Data.Char (digitToInt)
myFunction :: String -> Int
myFunction = foldr step 0
where step x y = (+) (digitToInt x) ( (*) y 2 )
Upvotes: 1