Yuki1112
Yuki1112

Reputation: 365

convert base 4 string to Decimal in Haskell

I have the following function that takes a string in the base of 4 and supposed to return a decimal integer, but my calculations seem to be off, so for "22" I need to get 10 but it's coming out as 5. Please help me fix this:

   base4Todec :: String -> Int
   base4Todec = foldr (\c s -> s * 4 + c) 0 . reverse . map c2i
       where c2i c = if c == '0' then 0 else 1

Note: I'm not allowed to use imports

Example: base4Todec "22" = 10

Upvotes: 1

Views: 148

Answers (1)

Will Ness
Will Ness

Reputation: 71070

Writing a function point-free is only good if it is clearer that way than the regular way. Here it doesn't look that way. So then,

base4Todec :: String -> Int
base4Todec cs  =  foldr (\c s -> s * 4 + c) 0 $ reverse $ map c2i cs
    where 
    c2i c  =  if c == '0' then 0 else 1

Not much change is it, but now the cause is clear:

    where 
    c2i c  =  if c == '0' then 0 else 1

Why 1? c2i '2' == 2 should hold, isn't it?

Your strings are not in binary. The maximum allowed digit for base 4 is 3.

By the way the foldr, reverse and map can all be fused into one foldl. Which is better changed to foldl' here (as is nearly always).

Upvotes: 1

Related Questions