This repository has been archived on 2025-07-20. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
fp/week3/problems.hs
2023-10-24 18:33:11 +01:00

47 lines
No EOL
1.4 KiB
Haskell

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]])