Skip to content

Instantly share code, notes, and snippets.

@jamesandariese
Last active September 6, 2016 09:09
Show Gist options
  • Save jamesandariese/4b66b21b296aa9731b7e9287a9eeb1b6 to your computer and use it in GitHub Desktop.
Save jamesandariese/4b66b21b296aa9731b7e9287a9eeb1b6 to your computer and use it in GitHub Desktop.
99 haskells
-- get last item in a list
myLast [] = error "out of range"
myLast (x : []) = x
myLast (_ : r) = myLast r
main = do
putStrLn(show(myLast [1,2,3]))
-- function to get second to last item in a list
mySTLast [] = error "out of range"
mySTLast (_ : []) = error "out of range"
mySTLast (x : _ : []) = x
mySTLast (_ : r) = mySTLast r
main = do
putStrLn (show (mySTLast [1,2,3]))
putStrLn (show (mySTLast [1]))
-- function to get an element at an arbirtary position in a list
-- this function is 1 indexed
elementAt [] _ = error "Index out of bounds"
elementAt (x : _) 1 = x
elementAt (_ : r) n = elementAt r (n-1)
main = do
putStrLn (show (elementAt [1,2,3] 2))
-- get the length of a list
-- accumulates the length in an inner function as it eats elements
myLength l = len' l 0
where
len' [] n = n
len' (_:r) n = len' r (n+1)
main = do
x <- return (myLength [1,2,3])
putStrLn(show x)
x <- return (myLength "hello pooperface")
putStrLn(show x)
-- reverse a list
-- this accumulates a reversed list as it goes in an inner function
myReverse l = reverse' l []
where
reverse' [] reversed = reversed
reverse' (e:r) reversed = reverse' r (e:reversed)
main = do
putStrLn(show (myReverse [1,2,3,4,5]))
@jamesandariese
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment