in smlnj how do you convert “string option” to “string”?

♀尐吖头ヾ 提交于 2019-12-05 23:08:12

As already pointed out you could use pattern matching to get the desired result. So, something like this:

fun foo(NONE) = ""
  | foo(SOME a) = a;

But you could spare the trouble and use Option.valOf function from SML library instead by just doing:

Option.valOf(SOME "my string"); (Or just valOf(SOME "my string"); as newacct pointed out in the comments.)

The "option" type in ML is like, say, Nullable in the .NET world. It is a discriminated union with two values, None and Some of 'a (for the generic 'a option type). To convert to a string, you need to get the value of 'a, which you can do via the normal pattern matching constructs.

Of course, if the value you have is None, there will be no string to retrieve. So, you need to handle the case where None appears, just as you might handle a null in other languages.

for Example:

val x = SOME "String";

(*You can simply get it, by doing so: *)

val stringfromoptionstring = case x of SOME s => s | NONE => "No String found";

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!