Difference between revisions of "99 questions/Solutions/3"
< 99 questions | Solutions
Jump to navigation
Jump to search
(Copied solution from 99 questions/1 to 10) |
Raph amiard (talk | contribs) (Adding a new version for elementAt) |
||
Line 25: | Line 25: | ||
| k < 1 = error "Index out of bounds" |
| k < 1 = error "Index out of bounds" |
||
| otherwise = elementAt' xs (k - 1) |
| otherwise = elementAt' xs (k - 1) |
||
+ | </haskell> |
||
+ | |||
+ | Alternative version: |
||
+ | |||
+ | <haskell> |
||
+ | elementAt'' :: [a] -> Int -> a |
||
+ | elementAt'' (x:_) 1 = x |
||
+ | elementAt'' (_:xs) i = elementAt xs (i - 1) |
||
+ | elementAt'' _ _ = error "Index out of bounds" |
||
</haskell> |
</haskell> |
Revision as of 23:38, 2 February 2011
(*) Find the K'th element of a list. The first element in the list is number 1.
This is (almost) the infix operator !! in Prelude, which is defined as:
(!!) :: [a] -> Int -> a
(x:_) !! 0 = x
(_:xs) !! n = xs !! (n-1)
Except this doesn't quite work, because !! is zero-indexed, and element-at should be one-indexed. So:
elementAt :: [a] -> Int -> a
elementAt list i = list !! (i-1)
Or without using the infix operator:
elementAt' :: [a] -> Int -> a
elementAt' (x:_) 1 = x
elementAt' [] _ = error "Index out of bounds"
elementAt' (_:xs) k
| k < 1 = error "Index out of bounds"
| otherwise = elementAt' xs (k - 1)
Alternative version:
elementAt'' :: [a] -> Int -> a
elementAt'' (x:_) 1 = x
elementAt'' (_:xs) i = elementAt xs (i - 1)
elementAt'' _ _ = error "Index out of bounds"