I'm trying to write a function contains
in SML/NJ:
fun contains(el: 'a, items: 'a list) =
if null items
then false
else ((hd items) = el) orelse contains(el, tl items)
I'm aware I could probably achieve the same end result using native list
functions, but this is for a MOOC that calls for not using any SML/NJ features beyond the basics it has covered thus far. The error I'm getting is:
solution.sml:10.9-10.24 Error: operator and operand don't agree [UBOUND match]
operator domain: ''Z * ''Z
operand: 'a * 'a
in expression:
hd items = el
I'm not 100% sure why I can't abstract over 'a
in the same way I can in 'a list
, I want 'a
to represent the same abstracted type in both instances. Am I doing it completely wrong?
In ML, you cannot in general compare values of generic type such as
'a
. However, there is a special kind of generic types written''a
, which stands for types that support equality testing using the=
operator.You can actually see that the error message is hinting at this by saying that
''Z * ''Z
does not match type'a * 'a
- you explicitly defined the function as generic using'a
, but the compiler would like it to be generic parameter''Z
which allows comparison.The following should do the trick: