문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top