Reputation:
I need to write an SML function that takes in as input a list of tuples (x and y coordinates) and an integer value. The function needs to return true if the integer is an x value in the list and false otherwise. For example if the list was:
val list = [(1,1),(2,4),(3,9),(4,16)];
The function would behave as follows:
memberOf(2, list) = true
memberOf(4, list) = true
memberOf(9, list) = false
Can somebody help me write a function that accomplishes this? I only need to test if the x value is in the list, the y value of the tuple is unimportant.
Thank you!
Upvotes: 1
Views: 7724
Reputation: 412
fun member_of (item, list) = List.exists (fn (x,y) => x = item) list
Upvotes: 2
Reputation: 1187
You can access the first argument of your tuple using #1 tuple
and the second one with #2 tuple
. So you check if the item exists either as the first argument or the second of the tuple list until you reach the end of your list.
(* fn : int * (int * int) list -> bool *)
fun exists_in (item: int, mylist: (int*int) list) =
if null mylist
then false
else if #1 (hd mylist) = item orelse #2 (hd mylist) = item
then true
else exists_in (item, tl mylist)
Upvotes: 1