You may think that, it
is very simple; I can call head function on a list and return the value. Be
cautious head function is a partial function, it thrown an exception on empty
list.
Prelude> head []
*** Exception:
Prelude.head: empty list
To make it work fine,
we need to check for list emptiness. Following function return ‘Just element’,
if the list is not empty, else Nothing.
getFirstEle list = if not (null list) then Just
(head list) else Nothing
Prelude> let getFirstEle list = if not (null list) then Just (head list) else Nothing Prelude> Prelude> getFirstEle [] Nothing Prelude> getFirstEle [1, 2, 3] Just 1 Prelude> getFirstEle "Hare Ram" Just 'H' Prelude>
No comments:
Post a Comment