Question

fun in_list (x : int, y : int list) =
if null y
then false
else if x=hd y then true
else in_list(x,tl y)

This is what my code currently looks like, it simply returns true if x appears in the the y list, false if not. The issue is I want it to be able to input "a" and ["a", "b", "c"] as well, or even have x be a list, and y be a list of lists. I am VERY new to ML (just started learning about it last week), and have searched for answers and cannot come up with anything.

Was it helpful?

Solution

If you change the first line to

fun in_list (x : ''a, y : ''a list) =

then it will behave as you want. Here ''a is an equality type variable that can stand for any type that supports the = operator.

You could also just leave out the types altogether and the most general correct type will be inferred.

OTHER TIPS

Types can always be omitted in function declarations, with is only one exception: where overloading of operators could cause ambiguity. An example is

fun square x = x*x

because the type of x could be either int or real. (It will default to int, maybe not what you want.)

The point is that there is only one function hd. But the operator * can refer to two quite different functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top