0

Suppose I have a function that returns a certain value when it satisfies a given condition and does not return any value when the condition is not satisfied.

e.g.

fun foo(n)= if n< 100000 then n else (something like exit function. We have it in other programming languages. Do we have something like that here?)

I initially wanted to write () but it says mismatch in two conditions of if or something.

Becoming more explicit, I want to write a function that takes a number, any number and combines to a list if it is valid integer and disregards it if it is not integer.

Mat
  • 202,337
  • 40
  • 393
  • 406
700resu
  • 259
  • 6
  • 16

2 Answers2

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.

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
sepp2k
  • 363,768
  • 54
  • 674
  • 675
1
fun foo n = if n < 1000000 then SOME n else NONE

beware that you can't use foo n directly as an integer but you have to use isSome and valOf or pattern matching to know in which case you are.

May be it would be better to pass your list as an argument and to append the value to it.

fun foo (n: int, xs: int list) =
   if n < 1000000 then n :: xs else xs
sonia
  • 106
  • 4