recursion - Converting list of base 3 digits to corresponding numerical value in Haskell -
below have defined function converts list of base-3 digits corresponding numerical value. example:
f "201" = (2 * 3^2) + (0 * 3^1) + (1 * 3^0) = 19 f "12" = 5 f "1202" = 47 f "120221" = 430
here definition using comprehension:
f :: string -> int f str = sum (listtofinal (stringtotuples str))
helper functions:
-- 1) converts "201" "102"
reverse "str"
-- 2) converts "102" 102
stringtoint :: string -> int stringtoint str = read str :: int
-- 3) converts 102 ['1','0','2']
inttolist :: int -> [int] inttolist 0 = [] inttolist x = inttolist (x `div` 10) ++ [x `mod` 10]
-- 4) converts "201" [(1,0),(0,1),(2,2)] using reverse, stringtoint, inttolist
stringtotuples :: string -> [(int,int)] stringtotuples str = zip (inttolist (stringtoint (reverse str))) [0..]
-- 5) converts [(1,0),(0,1),(2,2)] [1*3^0, 0*3^1, 2*3^2]
listtofinal :: [(int,int)] -> [int] listtofinal list = [ x * (3^y) | (x,y) <- list ]
now i'd recursion (well, using basic & library functions too, of course).
an idea: thinking of taking head of each element in list , multiplying 3^(length of string - 1). problem is, each recursive phone call powerfulness of 3 have decrease 1, e.g. given:
recursive_version "201" = (2 * 3^2) + (0 * 3^1) + (1 * 3^0)
how implement this?
here much simpler approach; note that, through utilize of foldl
, it's "implicitly" recursive, though. information, digittoint
exported data.char
.
import data.char import data.list ( foldl' ) --- horner x xs : value of polynomial 'xs' @ point 'x' horner :: int -> [int] -> int horner x = foldl' (\c1 c0 -> c1 * x + c0) 0 -- f s : integer representation in base of operations 3 string 's' f :: string -> int f = horner 3 . map digittoint
haskell recursion
No comments:
Post a Comment