Search code examples
iterationsml

Finding an element in a list SML


I am trying to learn beginner functions in ML. I am trying to write a function where you have an item and a list and you iterate through the list to see if there is a match. But right now I have no idea how to iterate through a list.

A function like

fun foundList(L, []) = false
    | foundList(L, x::xs) if L = xs then true;

I set the first line to false, because if the list is [ ] then it is empty and the statement is false?


Solution

  • You don't iterate, you recurse.

    A value is in the list if it's the first element or if it's in the tail of the list:

    fun foundList (_, []) = false
      | foundList (L, x::xs) = L = x orelse foundList (L, xs)