0

I need an algorithm that converts bin to dec

I found the following code in the Internet , but I just do not know , what some variables mean:

bin2dec :: [Int] -> Int
bin2dec n = foldl (\a x->2*a+x) 0 n

I already know foldl But what means (\a x->2*a+x) 0 n I do not know what \a x -> 2*a+x means and also " 0 n"

Could anyone please explain me how this function works ?

Thanks

Blnpwr
  • 1,793
  • 4
  • 22
  • 43

1 Answers1

0

foldl :: (a -> b -> a) -> a -> [b] -> a So basically a is first 0 and then the value that is carried throughout the fold. n is the list you pass into bin2dec and 0 is the object you start your fold on.

\a x -> 2 * a + x is a lamda function. It takes two variables, a and x and returns the value given on the right side of the arrow.

xZel
  • 60
  • 3
  • Oh thank you. I do not know lambda that much , can I write the code in a different way , like this: bin :: [Int] -> Int bin [] = 0 bin (x:xs) = foldl(2*xs+x) Doesn't it do the same thing ? But I get an error... – Blnpwr Nov 20 '13 at 20:53
  • You get an error because you need to give foldl a starting value, also a function. Look up the definition of foldl. Foldl's basecase will already pattern match for [], thus the [] pattern match you added should make a difference. The second line doesn't make any sense though and shouldn't compile. You don't give it a function or a base or a list. – xZel Nov 20 '13 at 20:58
  • What about: bin :: [Int] -> Int bin (x:xs) = (foldl (*) 2 (xs+x)) Still getting an error.. – Blnpwr Nov 20 '13 at 20:59
  • You could completely match the pattern that foldrl matches in this function or not, there isn't really another way to go about it. In what you just posted you are adding x, an Int, and xs, a list of Ints, which shouldn't compile. Look up the definition of foldl... – xZel Nov 20 '13 at 21:04
  • I don't understand this. fold has the (*) operator then 2 (to multiply) and then my list (x:xs). What does it need more ? Is the start value missin' ? – Blnpwr Nov 20 '13 at 21:21