Reputation: 1094
The following is getting an error:
(* Greetings, Earthlings! *)
fun greeting (some_name : string option) =
"Hello there, " ^
(if isSome some_name
then valOf some_name
else "you")
^ "!"
greeting("Tom")
The error is:
> $sml < main.sml
Standard ML of New Jersey v110.78 [built: Thu Aug 31 03:45:42 2017]
- = stdIn:3.5-9.16 Error: operator is not a function [tycon mismatch]
operator: string
in expression:
"!" greeting
I can't figure out where there is a type mistmatch.
Upvotes: 1
Views: 142
Reputation: 16145
This function is incidentally corresponds to the two-fer exercise of Exercism.io. Since my two favourite variants have not been show, I'd like to suggest either pattern matching directly in the argument of greeting
or using a library function:
fun greeting NONE = "Hello there, you!"
| greeting (SOME name) = "Hello there, " ^ name ^ "!"
fun greeting name =
"Hello there, " ^ Option.getOpt (name, "you") ^ "!"
A reason for liking the first one is that it uses case-matching just like case-of, but with less syntax. And a reason for liking the second one is that it avoids duplication of the part of the string that is the same, and does so using library functions, so you can expect readers to have seen this before.
Upvotes: 1
Reputation: 3920
Don't forget semi-colon after "!"
. SML assumes here that greeting("Tom")
is part of the function. So it interprets "!" greeting
as a function call.
Also your function argument is a string option
so don't forget the SOME
around "Tom"
. Here is the corrected code:
fun greeting (some_name : string option) =
"Hello there, " ^
(if isSome some_name
then valOf some_name
else "you")
^ "!";
print (greeting (SOME "Tom") ^ "\n");
print (greeting NONE ^ "\n");
Personally, I prefer using pattern matching in that situation, as it enhances readability in my opinion:
fun greeting (some_name : string option) =
"Hello there, " ^
(case some_name
of NONE => "you"
| SOME name => name)
^ "!";
Upvotes: 2