0

If I want to check if a string starts with a letter and the rest of the characters can either be a letter or number, how would I define a datatype that is defined by those conditions? Or would pattern matching be the better route and if so, how would I check that?

arizq29
  • 11
  • 5
  • You really wouldn't define a *datatype* to define that. Instead, write a function of type `string -> bool` that verifies the condition. Hint: it *starts with a letter* `andalso` *the rest of the string has a certain property*. Look at some of the SML standard library functions on strings and characters. You could explode the string to a list of characters and verify that the head of the list satisfies one property and the tail of the list another. – John Coleman May 01 '17 at 21:47
  • So would my function be along the lines of this? `fun isName(s : string): bool = val exp = String.explode(s) if ((isAlpha(hd exp)) andalso map(isAlphaNum, tl exp) then true else false` – arizq29 May 01 '17 at 22:21
  • Or should it be more along the lines of this? `fun isName(s : string): bool = val exp = String.explode(s) if isAlpha(hd exp) then let fun chk (x::xs) = if isAlphaNum x then chk(xs) else false | chk ([]) = true in chk(tl(exp)) end else false` – arizq29 May 01 '17 at 22:45

1 Answers1

0

If you don't care that using String.explode is a bit inefficient, then you can just define this predicate:

fun isName s = List.all Char.isAlpha (String.explode s)

Otherwise, you'd implement it via recursion over (the length of) the string itself.

Andreas Rossberg
  • 34,518
  • 3
  • 61
  • 72