Haskell 99 Problems – 03

Problem 3

(*) Find the K’th element of a list. The first element in the list is number 1.

Example:

* (element-at '(a b c d e) 3)
c

Example in Haskell:

Prelude> elementAt [1,2,3] 2
2
Prelude> elementAt "haskell" 5
'e'

 


— problem 3
— find elementat indexed location
elementat :: [a] -> Integer -> Maybe a
elementat [] _ = Nothing
elementat [x] 1 = Just x
elementat [x] _ = Nothing
elementat xs 1 = Just (head xs)
elementat (_:xs) n = elementat xs (n – 1)

view raw

h03.hs

hosted with ❤ by GitHub

 

 

 

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading