quela
quela

Reputation: 81

SML: How to determine if a list index is empty?

I'm trying to determine if my hd(tl list) is nothing or not. hd(tl list) = ? What would I use on the other side of the equality symbol?

Upvotes: 2

Views: 633

Answers (1)

Yawar
Yawar

Reputation: 11607

You can express the question 'is hd(tl list) nothing or not' as the equivalent question, 'does the list have less than two elements'. The latter question is easy to answer with SML in an elegant way using pattern matching on the list. Here is an interactive session:

$ poly
Poly/ML 5.7.1 Release
> fun isNothing [] = true
#   | isNothing [_] = true
#   | isNothing _ = false;
val isNothing = fn: 'a list -> bool

This function is saying, 'an empty list evaluates to true', 'a list with a single element evaluates to true', any other list evaluates to false. Tests:

> isNothing [];
val it = true: bool
> isNothing [1];
val it = true: bool
> isNothing [1, 2];
val it = false: bool
> isNothing [1, 2, 3];
val it = false: bool

Upvotes: 3

Related Questions