-
Notifications
You must be signed in to change notification settings - Fork 12
Lab 1 #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Lab 1 #7
Changes from all commits
9824e04
1b95577
8fef566
62d87aa
6cb4027
af7af0a
feb3f3a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,16 @@ | ||
| module FirstSteps | ||
| where | ||
| import Data.Word (Word8) | ||
| import GHC.Exts.Heap (GenClosure(key)) | ||
|
|
||
| -- xor x y находит "исключающее или" x и y | ||
| -- xor True False == True | ||
| -- xor True True == False | ||
|
|
||
| -- используйте сопоставление с образцом | ||
| xor :: Bool -> Bool -> Bool | ||
| xor x y = error "todo" | ||
| xor x y | x && not y || not x && y = True | ||
| | otherwise = False | ||
|
|
||
| -- max3 x y z находит максимум из x, y и z | ||
| -- max3 1 3 2 == 3 | ||
|
|
@@ -17,9 +19,17 @@ xor x y = error "todo" | |
| -- median3 1 3 2 == 2 | ||
| -- median3 5 2 5 == 5 | ||
| max3, median3 :: Integer -> Integer -> Integer -> Integer | ||
| max3 x y z = error "todo" | ||
| max3 x y z | x >= y && x >= z = x | ||
| | y >= x && y >= z = y | ||
| | z >= y && z >= x = z | ||
|
|
||
| median3 x y z = error "todo" | ||
| median3 x y z | (x > y && x <= z) || (x > z && x <= y) = x | ||
| | (y > z && y <= x) || (y > x && y <= z) = y | ||
| | (z > y && z <= x) || (z > x && z <= y) = z | ||
| | x == y = max x z | ||
| | x == z = max x y | ||
| | otherwise = max x y | ||
|
Comment on lines
+30
to
+31
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здесь менять не надо, но достаточно одной ветки. Видно ли, почему?
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здравствуйте! |
||
|
|
||
|
|
||
| -- Типы данных, описывающие цвета в моделях | ||
| -- RGB (https://ru.wikipedia.org/wiki/RGB), компоненты от 0 до 255 | ||
|
|
@@ -37,7 +47,14 @@ data CMYK = CMYK { cyan :: Double, magenta :: Double, yellow :: Double, black :: | |
| -- Заметьте, что (/) для Int не работает, и неявного преобразования Int в Double нет. | ||
| -- Это преобразование производится с помощью функции fromIntegral. | ||
| rbgToCmyk :: RGB -> CMYK | ||
| rbgToCmyk color = error "todo" | ||
| rbgToCmyk (RGB r g b) = CMYK c m y k | ||
| where | ||
| r' = fromIntegral r/255 | ||
| g' = fromIntegral g/255 | ||
| b' = fromIntegral b/255 | ||
| k = min(1-r') (min (1-g') (1-b')) | ||
| (c,m,y) | k == 1 = (0,0,0) | ||
| | otherwise = ((1 - r' - k)/(1-k), (1-g'-k)/(1-k), (1-b'-k)/(1-k)) | ||
|
|
||
| -- geomProgression b q n находит n-й (считая с 0) член | ||
| -- геометрической прогрессии, нулевой член которой -- b, | ||
|
|
@@ -47,11 +64,13 @@ rbgToCmyk color = error "todo" | |
| -- используйте рекурсию | ||
| -- не забудьте случаи n < 0 и n == 0. | ||
| geomProgression :: Double -> Double -> Integer -> Double | ||
| geomProgression b q n = error "todo" | ||
| geomProgression b q n | n < 0 = 0.0 | ||
| | n == 0 = b | ||
| | n>0 = q * geomProgression b q (n-1) | ||
|
|
||
| -- coprime a b определяет, являются ли a и b взаимно простыми | ||
| -- (определение: Целые числа называются взаимно простыми, | ||
| -- если они не имеют никаких общих делителей, кроме +/-1) | ||
| -- если они не имеют никаких общиsх делителей, кроме +/-1) | ||
| -- coprime 10 15 == False | ||
| -- coprime 12 35 == True | ||
|
|
||
|
|
@@ -64,4 +83,9 @@ geomProgression b q n = error "todo" | |
| -- обрабатываете отрицательные числа) | ||
| -- https://hackage.haskell.org/package/base-4.9.0.0/docs/Prelude.html | ||
| coprime :: Integer -> Integer -> Bool | ||
| coprime a b = error "todo" | ||
| nod :: Integer -> Integer -> Integer | ||
|
|
||
| nod a b | a == 0 || b == 0 = a + b | ||
| | otherwise = if a > b then nod b (a `rem` b) else nod a (b `rem` a) | ||
|
|
||
| coprime a b = nod a b == 1 || nod a b == -1 | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,8 @@ | ||
| {-# OPTIONS_GHC -Wno-incomplete-patterns #-} | ||
| module Lists where | ||
|
|
||
| import Data.List (delete) | ||
| import Data.Bits (Bits(xor)) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это тоже похоже на случайно оставленное после редактирования (а вот |
||
| -- вектор задаётся списком координат | ||
| newtype Point = Point [Double] deriving (Eq, Show, Read) | ||
|
|
||
|
|
@@ -10,22 +13,49 @@ newtype Point = Point [Double] deriving (Eq, Show, Read) | |
|
|
||
| -- используйте рекурсию и сопоставление с образцом | ||
| distance :: Point -> Point -> Double | ||
| distance x y = error "todo" | ||
| -- distance (Point x) (Point y) | length x /= length y = error "Число компонент вектора должно быть одинаковым" | ||
| -- | otherwise = sqrt $ sum [(a-b)^2 |(a, b) <- zip x y] | ||
|
|
||
| -- Вспомогательная функция для подсчета суммы квадратов | ||
| squareSum :: Point -> Point -> Double | ||
| squareSum (Point []) (Point []) = 0 | ||
| squareSum (Point [x]) (Point [y]) = (x - y)^2 | ||
| squareSum (Point (x:xs)) (Point (y:ys)) = (x-y)^2 + squareSum (Point xs) (Point ys) | ||
|
|
||
| distance (Point x) (Point y) = if length x /= length y then error "Число компонент вектора должно быть одинаковым" | ||
| else sqrt $ squareSum (Point x) (Point y) | ||
|
|
||
| -- intersect xs ys возвращает список, содержащий общие элементы двух списков. | ||
| -- intersect [1, 2, 4, 6] [5, 4, 2, 5, 7] == [2, 4] (или [4, 2]!) | ||
| -- intersect [1, 2, 4, 6] [3, 5, 7] == [] | ||
|
|
||
| -- используйте рекурсию и сопоставление с образцом | ||
| intersect :: [Integer] -> [Integer] -> [Integer] | ||
| intersect xs ys = error "todo" | ||
| intersect [] _ = [] | ||
| intersect _ [] = [] | ||
| intersect (x:xs) ys | ||
| | x `elem` ys = x : intersect xs (delete x ys) | ||
| | otherwise = intersect xs ys | ||
|
|
||
| -- zipN принимает список списков и возвращает список, который состоит из | ||
| -- списка их первых элементов, списка их вторых элементов, и так далее. | ||
| -- zipN [[1, 2, 3], [4, 5, 6], [7, 8, 9]] == [[1, 4, 7], [2, 5, 8], [3, 6, 9]] | ||
| -- zipN [[1, 2, 3], [4, 5], [6]] == [[1, 4, 6], [2, 5], [3]] | ||
|
|
||
| firsts :: [[a]] -> [a] | ||
| firsts [] = [] | ||
| firsts ([]:xss) = [] | ||
| firsts ((x:xs):xss) = x : firsts xss | ||
|
|
||
| rests :: [[a]] -> [[a]] | ||
| rests [] = [] | ||
| rests ([]:xss) = [] | ||
| rests ((x:xs):xss) = xs : rests xss | ||
|
|
||
| zipN :: [[a]] -> [[a]] | ||
| zipN xss = error "todo" | ||
| zipN [] = [] | ||
| zipN xss | all null xss = [] | ||
| | otherwise = firsts xss : zipN (rests xss) | ||
|
|
||
| -- Нижеперечисленные функции можно реализовать или рекурсивно, или с помощью | ||
| -- стандартных функций для работы со списками (map, filter и т.д.) | ||
|
|
@@ -37,23 +67,33 @@ zipN xss = error "todo" | |
| -- find (> 0) [-1, 2, -3, 4] == Just 2 | ||
| -- findLast (> 0) [-1, 2, -3, 4] == Just 4 | ||
| -- find (> 0) [-1, -2, -3] == Nothing | ||
| find, findLast :: (a -> Bool) -> [a] -> Maybe a | ||
| find f xs = error "todo" | ||
| findLast f xs = error "todo" | ||
| find,findLast :: (a -> Bool) -> [a] -> Maybe a | ||
| findFilter :: (a->Bool) -> [a] -> Maybe a | ||
| find _ [] = Nothing | ||
| find f (x:xs) | ||
| | f x = Just x | ||
| | otherwise = find f xs | ||
|
|
||
| findLast f xs = find f (reverse xs) | ||
|
|
||
| findFilter _ [] = Nothing | ||
| findFilter f xs = case filter f xs of | ||
| [] -> Nothing | ||
| (x:_) -> Just x | ||
|
|
||
| -- mapFuncs принимает список функций fs и возвращает список результатов | ||
| -- применения всех функций из fs к x. | ||
| -- mapFuncs [\x -> x*x, (1 +), \x -> if even x then 1 else 0] 3 == [9, 4, 0] | ||
| mapFuncs :: [a -> b] -> a -> [b] | ||
| mapFuncs fs x = error "todo" | ||
| mapFuncs fs x = map (\ f -> f x) fs | ||
|
|
||
| -- satisfiesAll принимает список предикатов (функций, возвращающих Bool) preds | ||
| -- и возвращает True, если все они выполняются (т.е. возвращают True) для x. | ||
| -- Полезные стандартные функции: and, all. | ||
| -- satisfiesAll [even, \x -> x rem 5 == 0] 10 == True | ||
| -- satisfiesAll [] 4 == True (кстати, почему?) | ||
| satisfiesAll :: [a -> Bool] -> a -> Bool | ||
| satisfiesAll preds x = error "todo" | ||
| satisfiesAll preds x = all id (mapFuncs preds x) | ||
|
|
||
| -- Непустой список состоит из первого элемента (головы) | ||
| -- и обычного списка остальных элементов | ||
|
|
@@ -67,3 +107,21 @@ data NEL a = NEL a [a] deriving (Eq, Show, Read) | |
| -- zipNel :: NEL a -> NEL b -> ??? | ||
| -- listToNel :: [a] -> ??? | ||
| -- nelToList :: NEL a -> ??? | ||
|
|
||
| tailNel :: NEL a -> [a] | ||
| tailNel (NEL _ xs) = xs | ||
|
|
||
| lastNel :: NEL a -> a | ||
| lastNel (NEL x []) = x | ||
| lastNel (NEL a (x:xs)) = lastNel (NEL x xs) | ||
|
|
||
| zipNel :: NEL a -> NEL b -> NEL (a,b) | ||
| zipNel (NEL x xs) (NEL y ys) = NEL (x,y) (zip xs ys) | ||
|
|
||
| listToNel :: [a] -> Maybe (NEL a) | ||
| listToNel [] = Nothing | ||
| listToNel (x:xs) = Just (NEL x xs) | ||
|
|
||
| nelToList :: NEL a -> [a] | ||
| nelToList (NEL a xs) = a:xs | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это случайность? Вроде нигде не используется.