bock.steve
bock.steve

Reputation: 231

Variable types for parameters in SML

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.

Upvotes: 1

Views: 231

Answers (2)

Lawrence Paulson
Lawrence Paulson

Reputation: 629

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.

Upvotes: 0

sepp2k
sepp2k

Reputation: 370465

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.

Upvotes: 2

Related Questions