SHARE
TWEET

Součin dlouhých čísel v Haskellu

tomasslavicek Jun 28th, 2011 165 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Soucin dlouhych cisel
  2. --   parametry: znamenko (1/-1), cifry [Int], pozice des. carky od 1. cifry
  3. --   test -123.14*1.2:   multBig (-1,[1,2,3,1,4],3) (1,[1,2],1)
  4. type BigNum = (Int, [Int], Int)
  5. multBig :: BigNum -> BigNum -> BigNum
  6. multBig (sign1,s1,d1) (sign2,s2,d2) = (sign1 * sign2, finalNum, finalD)
  7.     where finalNum = reverse $ multB (reverse s1) (reverse s2) 0
  8.           finalD = length finalNum - (length s1 - d1 + length s2 - d2)
  9.  
  10. -- Vynasobi dva otocene seznamy cisel
  11. --   parametry: prvni seznam (odzadu), ukrajujici se druhy seznam (odzadu), posunuti od zacatku
  12. multB :: [Int] -> [Int] -> Int -> [Int]
  13. multB _ [] _ = []
  14. multB s1 (n:ns) p = normNums [a+b | (a,b) <- zipPlus line otherLines] 0
  15.     where line = [0|_<-[1..p]] ++ multByNum s1 n
  16.           otherLines = multB s1 ns (p+1)
  17.  
  18. -- Vynasobi seznam cislem
  19. multByNum :: [Int] -> Int -> [Int]
  20. multByNum s n =
  21.     let nums = [n*x | x <- s]
  22.     in normNums nums 0
  23.  
  24. -- Posle dal desitkove prebytky (druhy parametr = preteceni)    
  25. normNums :: [Int] -> Int -> [Int]
  26. normNums [] 0 = []
  27. normNums [] n = [n]
  28. normNums (x:xs) n = ((x+n) `mod` 10) : (normNums xs ((x+n) `div` 10))
  29.  
  30. -- zipPlus - jako zip (udela dvojice), plus doplni kratsi seznam nulami
  31. zipPlus :: (Num a, Num b) => [a] -> [b] -> [(a,b)]
  32. zipPlus [] [] = []
  33. zipPlus [] (x:xs) = (0,x):(zipPlus [] xs)
  34. zipPlus (x:xs) [] = (x,0):(zipPlus xs [])
  35. zipPlus (x:xs) (y:ys) = (x,y):(zipPlus xs ys)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top