Week 3 exercises

This commit is contained in:
akp 2023-10-24 18:33:11 +01:00
parent c0f99a3821
commit 807dce7ea7
No known key found for this signature in database
GPG key ID: CF8D58F3DEB20755
3 changed files with 76 additions and 21 deletions

View file

@ -1,21 +0,0 @@
-- setting the "warn-incomplete-patterns" flag asks GHC to warn you
-- about possible missing cases in pattern-matching definitions
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
-- see https://wiki.haskell.org/Safe_Haskell
{-# LANGUAGE Safe #-}
module Homework3 (gasUsage , luhnDouble , luhn) where
import Types
gasUsage :: (Fractional a, Ord a) => a -> Classification
gasUsage = undefined
luhnDouble :: Int -> Int
luhnDouble = undefined
luhn :: Int -> Int -> Int -> Int -> Bool
luhn = undefined

29
week3/homework.hs Normal file
View file

@ -0,0 +1,29 @@
-- setting the "warn-incomplete-patterns" flag asks GHC to warn you
-- about possible missing cases in pattern-matching definitions
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
-- see https://wiki.haskell.org/Safe_Haskell
{-# LANGUAGE Safe #-}
module Homework3 (gasUsage , luhnDouble , luhn) where
import Types
gasUsage :: (Fractional a, Ord a) => a -> Classification
gasUsage g | g < 3 = Low
| 3 <= g && g < 5 = Medium
| 5 <= g && g < 7 = High
| otherwise = SuperHigh
luhnDouble :: Int -> Int
luhnDouble x = let y = x * 2 in
if y > 9 then y - 9 else y
luhn :: Int -> Int -> Int -> Int -> Bool
luhn a b c d = let x = [a, b, c, d] in
sum (
map
(\(i, y) -> if i `mod` 2 == 0 then luhnDouble y else y)
(zip [1..4] (reverse x))
) `mod` 10 == 0

47
week3/problems.hs Normal file
View file

@ -0,0 +1,47 @@
aand :: [Bool] -> Bool
aand x = aandImpl x True
aandImpl :: [Bool] -> Bool -> Bool
aandImpl (x:xs) cursor = aandImpl xs (cursor && x)
aandImpl _ cursor = cursor
cconcat :: [[a]] -> [a]
cconcat [] = []
cconcat (x:xs) = x ++ (cconcat xs)
rreplicate :: Int -> a -> [a]
rreplicate 1 t = [t]
rreplicate n t = [t] ++ (rreplicate (n-1) t)
(!!!) :: [a] -> Int -> a
(!!!) (x:_) 0 = x
(!!!) (x:xs) n = xs !!! (n-1)
isElem :: Eq a => a -> [a] -> Bool
isElem y [x] = x == y
isElem y (x:xs) = x == y || (isElem y xs)
merge :: Ord a => [a] -> [a] -> [a]
merge [a] [b] | a < b = [a, b]
| otherwise = [b, a]
merge [a] (b:bs) | a < b = [a] ++ ([b] ++ bs)
| otherwise = [b] ++ (merge [a] bs)
merge (a:as) [b] | a < b = [a] ++ (merge as [b])
| otherwise = [b] ++ ([a] ++ as)
merge (a:as) (b:bs) | a < b = [a] ++ (merge as ([b] ++ bs))
| otherwise = [b] ++ (merge ([a] ++ as) bs)
isPythTriple :: (Int, Int, Int) -> Bool
isPythTriple (x, y, z) = x^2 + y^2 == z^2
pyths :: Int -> [(Int, Int, Int)]
pyths n = [(x, y, z) | x <- [1..n], y <- [1..n], z <- [1..n], isPythTriple (x, y, z)]
factors :: Int -> [Int]
factors n = [x | x <- [1..n], n `mod` x == 0]
perfects :: Int -> [Int]
perfects n = [x | x <- [1..n], (sum (tail (reverse (factors x)))) == x]
scalarProduct :: [Int] -> [Int] -> Int -> Int
scalarProduct a b n = sum ([(a!!i)*(b!!i) | i <- [0..n-1]])