Conversation
Chapter 1
vrom911
left a comment
There was a problem hiding this comment.
Congrats with finishing these chapters 🎉
| -} | ||
| closestToZero :: Int -> Int -> Int | ||
| closestToZero x y = error "closestToZero: not implemented!" | ||
| closestToZero x y = if (abs x) < (abs y) then x else y |
There was a problem hiding this comment.
() are redundant here. I see how it can be confusing to see when to use them and when not to use, especially in the beginning. But it's usually better to remove redundant brackets for cleaner code 🧹
| closestToZero x y = if (abs x) < (abs y) then x else y | |
| closestToZero x y = if abs x < abs y then x else y |
| sumLast2 n = error "sumLast2: Not implemented!" | ||
|
|
||
| sumLast2 :: Int -> Int | ||
| sumLast2 n = (lastDigit n) + secondLastDigit |
There was a problem hiding this comment.
Nice reusage of previous lastDigit function! 👏🏼
I see that you have already a var to represent this bit – lastD, you can reuse it here too!
| sumLast2 n = (lastDigit n) + secondLastDigit | |
| sumLast2 n = lastD + secondLastDigit |
| | absN < 10 = absN | ||
| | otherwise = firstDigit (div absN 10) | ||
| where | ||
| absN = abs n |
There was a problem hiding this comment.
Very elegant to use where clause here 👍🏼
| takeEven l = go True l | ||
| where | ||
| go :: Bool -> [a] -> [a] | ||
| go _ [] = [] | ||
| go True (x:xs) = x : go False xs | ||
| go False (_:xs) = go True xs |
There was a problem hiding this comment.
Nice idea on the helper functions 👍
Alternatively, you could use pattern matching in takeEven instead. As you need to take every second element, it is possible to represent with a few pattern matching clauses 🙂
| -} | ||
| smartReplicate :: [Int] -> [Int] | ||
| smartReplicate l = error "smartReplicate: Not implemented!" | ||
| smartReplicate l = concat (map (\x -> replicate x x) l) |
There was a problem hiding this comment.
Great! 👍🏼
If you want to write this function even more elegantly, you can use the standard function concatMap which is a combination of concat and map as the name suggests 🙂
After that, you could notice, that you would be able to eta-reduce on the last argument :)
| go :: Int -> [[Int]] -> [[Int]] | ||
| go _ [] = [] | ||
| go n (x:xs) = if n `elem` x | ||
| then x : go n xs | ||
| else go n xs |
There was a problem hiding this comment.
Nice go! It is actually the standard filter function, that you can use instead of the custom go, but it is correct!
Solutions for Chapter 1 and 2
cc @vrom911