Pierre P.
Pierre P.

Reputation: 1065

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.

Upvotes: 3

Views: 3335

Answers (4)

Sanaz Najian
Sanaz Najian

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

melpomene
melpomene

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

zeronone
zeronone

Reputation: 3041

Assuming the input is a list of 1s and 0s.

bin2num :: [Int] -> Int
bin2num list = go list 0
  where go []     _ = 0
        go (x:xs) n = (x*(2^n)) + (go xs (n+1))

Upvotes: 0

martin
martin

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

Related Questions