As an F# newbie, I am trying to implement a simple function which takes an index and a list as parameters then returns the list value of the given index.
let rec getElementAtIndex (index : int) (list : 'a list) =
match index, list with
| _ ,[] -> failwith "index is greater than number of elements in list.."
| _, _ when index < 0 -> failwith "index is less than 0."
| 0, (first::_) -> first
| _, (_::rest') -> getElementAtIndex (index - 1) rest'
My solution works fine but when I give the index parameter greater than the list size and when I give an empty list as parameter, in both situations goes in to the same condition which is
| _ ,[] -> failwith "index is greater than number of elements in list."
How can i avoid this and check if the list is empty and given index is greater than list size separately without using .net library methods?
Any help would be appreciated
List.length
.length
yourself.