简体   繁体   中英

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM