Question

i'm having some trouble with one part of a function. My function needs an input string of at least 3 characters to avoid error, to do this a want to add one or two "." in the var. Looks something like this:

fun function(a, b) =
if size(a) < 2 then a ^ "  " else if size(a) < 3 then a ^ " "
if size(b) < 2 then b ^ "  " else if size(b) < 3 then b ^ " "

the function code;

my question is, how do i end the first if line? as it is now the secound if statement get an error.

thanks / joakim

Was it helpful?

Solution

Firstly, this doesn't make any sense. An if-then-else must have all three parts: you can not omit the else, which your trailing if-then clearly does.

Secondly, multiple statements (separated by ;) are only useful when there are side-effects, which there are not. You may change your code to

fun function (a, b) =
  ( if size a < 2 then a ^ "  " else
    if size a < 3 then a ^ " "  else
                       a
  ; if size b < 2 then b ^ "  " else
    if size b < 3 then b ^ " "  else
                       b
  )

but the result of the first statement will be discarded, and is completely useless.

Perhaps you want something more like

fun padLeft (n, a) =
    if size a < n
    then a ^ CharVector.tabulate(n - size a, fn _ => #" ")
    else a

fun function1 (a, b) = (padLeft (3, a), padLeft (3, b))
fun function2 (a, b) = (print (padLeft (3, a)); print (padLeft (3, b)))

where function1 returns a pair using both inputs, and function2 returns unit but has a visible side-effect using both inputs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top