DimitrisChousiadas
DimitrisChousiadas

Reputation: 133

How to check if a value is a list in ML?

I am trying to write a function in ML (SML/NJ) to check if a value is a list or not.

fun is_list [] = true | is_list (h::t) = true | is_list _ = false;

I expected the is_list function to be a 'a -> bool function. Instead, I get a match redundant error. Why is that? And how should the function be written?

thanks!

Upvotes: 1

Views: 730

Answers (1)

Andreas Rossberg
Andreas Rossberg

Reputation: 36088

ML is a typed language. You can't write such a function. If you ever feel the need for it then you are approaching the problem from the wrong direction. The only way in ML to distinguish different cases at runtime is by using datatypes (and you can define your own datatypes if you need to allow heterogeneous types in some parts of your program).

See also my reply to a similar question, for why this restriction is a feature.

Upvotes: 2

Related Questions