99 questions/Solutions/3
From HaskellWiki
< 99 questions  Solutions(Difference between revisions)
(Reformat solution to fit on page) 

(2 intermediate revisions by 2 users not shown) 
Latest revision as of 02:32, 15 June 2016
(*) 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 !! (n1)
Except this doesn't quite work, because !! is zeroindexed, and elementat should be oneindexed. So:
elementAt :: [a] > Int > a elementAt list i = list !! (i1)
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"
This does not work correctly on invalid indexes and infinite lists, e.g.:
elementAt'' [1..] 0
A few more solutions using prelude functions:
elementAt'' xs n  length xs < n = error "Index out of bounds"  otherwise = fst . last $ zip xs [1..n] elementAt''' xs n = head $ foldr ($) xs $ replicate (n  1) tail  Negative indices not handled correctly:  Main> elementAt''' "haskell" (1)  'h' elementAt'''' xs n  length xs < n = error "Index out of bounds"  otherwise = last $ take n xs elementAt''''' xs n  length xs < n = error "Index out of bounds"  otherwise = head . reverse $ take n xs elementAt'''''' xs n  length xs < n = error "Index out of bounds"  otherwise = head $ drop (n  1) xs
elementAt_w'
elementAt_w'pf = (last .) . take . (+ 1)
elementAt_w'pf
elementAt_w'pf' = flip $ (last .) . take . (+ 1)