efene programming language

“fixing” if expressions in erlang

In erlang the if expression works the same way as guards, from the erlang documentation:

The set of valid guard expressions (sometimes called guard tests) is a subset of the set of valid Erlang expressions. The reason for restricting the set of valid expressions is that evaluation of a guard expression must be guaranteed to be free of side effects.

that means that we can’t make a function call in the if like this:

if foo(X) -> something

the solution is to use case, but it’s a little more verbose an most people are used to the if expression.

I thought a lot about making the if expression work more like “the mainstream languages” and today I finally decided to implement it.

In previous versions of efene the if expression was the same as in erlang, but from today the things changed.

The erlang if expression is now a when expression in efene, they work the same, produce the same code and since ifs in erlang are like guards, using when makes a lot of sence.

The efene if expression is now converted internally to a set of nested case statements that produce the same result.

This ifene code:

main = fn ()
    if call(10) > 0
        somevalue
    else if othercall(21) != 4
        notfour
    else if 23 < 6
        othervalue
    else
        elsevalue

Converted with fnc -t erl produces:

 
main() ->
    case call(10) > 0 of
      true -> somevalue;
      false ->
	  case othercall(21) /= 4 of
	    true -> notfour;
	    false ->
		case 23 < 6 of
		  true -> othervalue;
		  false -> elsevalue
		end
	  end
    end.

A when expression in efene:

main = fn ()
    when 1 > 2
        somevalue
    else when 23 < 6
        othervalue
    else
        elsevalue

Converted to erlang produces:

 
main() ->
    if 1 > 2 -> somevalue;
       23 < 6 -> othervalue;
       true -> elsevalue
    end.

I hope the new if expression in efene removes another “this is weird” moment when approaching erlang and trying to make a function call in an if statement. For erlang programmers, the good old if is available if needed as the when expression


To Tumblr, Love Metalab