0

特定の条件を満たす場合は特定の値を返し、条件が満たされない場合は値を返さない関数があるとします。

例えば

fun foo(n)= if n <100000 then n else(exit関数のようなもの。他のプログラミング言語にもあります。ここにそのようなものはありますか?)

最初は()を書きたかったのですが、ifか何かの2つの条件で不一致が表示されます。

もっと明確になって、私は、数値、任意の数値を取り、それが有効な整数である場合はリストに結合し、整数でない場合はそれを無視する関数を書きたいと思います。

4

2 に答える 2

5

In SML a function always has to return a value¹. One way to represent a function that may or may not have a useful result would be using the OPTION type. Using OPTION your function would return SOME value if it has something useful to return, or NONE if it does not.

For your particular use-case another alternative would be to take the list as a second argument and then either return the result prepended to the list or the list unchanged.

¹ In fact I'm not aware of any language where a non-void function is allowed to not return a value (without invoking undefined behavior). In some languages you can return null in place of a proper return value, but in most languages that isn't allowed for functions with return type int. Either way SML doesn't have a null value.

于 2012-10-21T11:52:50.640 に答える
1
fun foo n = if n < 1000000 then SOME n else NONE

foo n を整数として直接使用することはできませんが、isSome と valOf またはパターン マッチングを使用して、どちらの場合であるかを知る必要があることに注意してください。

リストを引数として渡し、それに値を追加する方が良いかもしれません。

fun foo (n: int, xs: int list) =
   if n < 1000000 then n :: xs else xs
于 2013-01-24T21:20:32.393 に答える