Skip to content

Instantly share code, notes, and snippets.

@vvv
Forked from rajanikantchirmade/listsum.hs
Last active August 24, 2017 09:41
Show Gist options
  • Save vvv/1ec38073b964c527251dfc29e3d23fc5 to your computer and use it in GitHub Desktop.
Save vvv/1ec38073b964c527251dfc29e3d23fc5 to your computer and use it in GitHub Desktop.
listsum :: Num a => [a] -> a
listsum [] = 0
listsum (x:xs) = x + listsum xs
main :: IO ()
main = print $ listsum [1..5]
mykth :: (Ord n, Num n) => [a] -> n -> a
mykth [] _ = error "Invalid argument"
mykth (x:_) 1 = x
mykth (_:xs) k =
if k < 1
then error "Index is out of boundaries"
else mykth xs (k-1)
mylast :: [a] -> a
mylast = head . reverse
main :: IO ()
main = do
print $ mylast [1..4]
print $ mylast "rajanikant"
secondlast :: [a] -> a
secondlast xs = case reverse xs of
(_:x:_) -> x
_ -> error "List is too short"
main :: IO ()
main = print $ secondlast [1..5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment