Advertisement
Terrium

Untitled

Apr 30th, 2020
1,283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class IntArray a where
  2.   -- Получение элемента по индексу
  3.   getElem :: a -> Int -> Int
  4.  
  5.   -- Установка элемента по индексу
  6.   setElem :: a -> Int -> Int -> a
  7.  
  8.   -- Создание массива из нулей
  9.   createZeroesIntArray :: Int -> a
  10.  
  11.   -- Увеличение значения элкмента по индексу на единицу
  12.   incrementElem :: a -> Int -> a
  13.   incrementElem intArray index = setElem intArray index ((getElem intArray index) + 1)
  14.  
  15. -- Реализация для [Int]
  16. getListElem :: [Int] -> Int -> Int
  17. getListElem list index = list !! index
  18.  
  19. setListElem :: [Int] -> Int -> Int -> [Int]
  20. setListElem list index newValue = (take index list) ++ [newValue] ++ (drop (index + 1) list)
  21.  
  22. createZeroesList :: Int -> [Int]
  23. createZeroesList count = replicate count 0
  24.  
  25. incrementListAt :: [Int] -> Int -> [Int]
  26. incrementListAt list index = setListElem list index ((getListElem list index) + 1)
  27.  
  28. instance IntArray [Int] where
  29.   getElem = getListElem
  30.   setElem = setListElem
  31.   createZeroesIntArray = createZeroesList
  32.  
  33. --Реализация для [Map]
  34.  
  35. getMapElem :: (Map.IntMap Int) -> Int -> Int
  36. getMapElem map index = map Map.! index
  37.  
  38. setMapElem :: (Map.IntMap Int) -> Int -> Int -> (Map.IntMap Int)
  39. setMapElem map index value = Map.insert index value map
  40.  
  41. createZeroesMap :: Int -> (Map.IntMap Int)
  42. createZeroesMap count = Map.fromList [(index, 0) | index <- [0..count]]
  43.  
  44. instance IntArray (Map.IntMap Int) where
  45.   getElem = getMapElem
  46.   setElem = setMapElem
  47.   createZeroesIntArray = createZeroesMap
  48.  
  49. incrementMapAt :: (Map.IntMap Int) -> Int -> (Map.IntMap Int)
  50. incrementMapAt list index = setMapElem list index ((getMapElem list index) + 1)
  51.  
  52. fill :: forall a. IntArray a => a -> a
  53. fill list = foldl (\zs -> \i ->  incrementElem zs i) (createZeroesIntArray ((maximum list) + 1)) list
  54.  
  55. fillList :: [Int] -> [Int]
  56. fillList list = foldl (\zs -> \i ->  incrementListAt zs i) (createZeroesList ((maximum list) + 1)) list
  57.  
  58. fillMap :: (Map.IntMap Int) -> (Map.IntMap Int)
  59. fillMap list = foldl (\zs -> \i ->  incrementMapAt zs i) (createZeroesMap ((maximum list) + 1)) list
  60.  
  61. main :: IO ()
  62. main = putStrLn $ show (fill @[Int] [0,2,4,2])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement