Created
June 11, 2024 17:17
-
-
Save austin362667/6daa8696899df0829471832028498ed3 to your computer and use it in GitHub Desktop.
FLOLAC 2024 [Problem Set](https://gist.github.com/genetsai95/8cecea25a4c4d5c7b9b9275b4ab6f203)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
-- WIP: Haven't read ch6, ch8 in [Learn You a Haskell for Great Good]. | |
-- 0. | |
penultimate xs = last (init xs) | |
-- 1. | |
antepenultimate xs = penultimate (init xs) | |
-- 2. | |
-- `shiftLeft` is a helper function for `rotateLeft` | |
shiftLeft [] = [] | |
shiftLeft (x:xs) = xs ++ [x] | |
rotateLeft n xs | |
| n == 0 = xs | |
| n > 0 = rotateLeft (n-1) (shiftLeft xs) | |
-- TODO: check if value `n` is negative or not | |
-- 3. | |
insertElem x k xs | |
| k < 0 = error "Neg K" | |
| k >= 0 = (take k xs) ++ [x] ++ (drop k xs) | |
-- No need to check if index K is larger than length of list xs | |
-- 4. | |
-- palindrome :: Eq a => [a] -> Bool | |
palindrome xs = xs == reverse xs | |
-- 5. | |
power x y | |
| y == 0 = 1 | |
| y == 1 = x | |
| y > 1 = x * power x (y-1) | |
-- 6. | |
-- `convertBits` is a helper function for `convertBinaryDigit` | |
convertBits [] _ = 0 | |
convertBits (b:bs) n = | |
(if b then 2^n else 0) + convertBits bs (n - 1) | |
convertBinaryDigit bits = convertBits bits (length bits - 1) | |
-- 7. | |
fib n = reverse (map fibN [0..n-1]) | |
where | |
fibN 0 = 0 | |
fibN 1 = 1 | |
fibN k = fibN (k - 1) + fibN (k - 2) | |
-- 8. | |
-- mapFirst :: (a -> b) -> (a, c) -> (b, c) | |
mapFirst f (x,y) = (f x, y) | |
-- 9. | |
-- 10. | |
-- 11. | |
-- 12. | |
-- 13. | |
-- 14. | |
-- 15. | |
-- the main function | |
main :: IO () | |
main = do | |
print (penultimate [1,2,3,4,5]) -- 4 | |
print (antepenultimate [1,2,3,4,5]) -- 3 | |
print (shiftLeft [1,2,3,4,5]) -- [2,3,4,5,1] | |
print (rotateLeft 3 [1,2,3,4,5]) -- [4,5,1,2,3] | |
print (rotateLeft 5 [1,2,3,4,5]) -- [1,2,3,4,5] | |
print (insertElem 3 3 [1,2,3,4,5]) -- [1,2,3,3,4,5] | |
print (insertElem 3 30 [1,2,3,4,5]) -- [1,2,3,4,5,3] | |
print(palindrome [1,2,3,4,5,4,3,2,1]) -- True | |
print(palindrome [1,2,3,4,5,4,3,2,2]) -- False | |
print(power 3 4) -- 81 | |
print(power 4 3) -- 64 | |
print(convertBinaryDigit [True, False, False]) -- 4 | |
print(fib 5) -- [3,2,1,1,0] | |
print(mapFirst (+7) (4, True)) -- (11, True) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment