else if, switch case, or pattern matching?

Pixilang programming language
Post Reply
User avatar
Logickin λ
Posts: 169
Joined: Sat Sep 08, 2018 8:31 pm
Contact:

else if, switch case, or pattern matching?

Post by Logickin λ »

Have been used pixilang for a week, and it is really a fun language to play with, but currently I have faced with an issue about control flow.

Seems pixilang has no way to do "else if", which can be useful when we need to a lot of range check.

I understand we can use if and else only:

Code: Select all

if a >= 0 && a < 10 { 
	function a 
} else {
	if a >= 10 && a < 20 { 
		function b
	} else {
		if a >= 20 && a < 30 { 
			function c
		} else {
			if a >= 30 && a < 40 { 
				function d
			} else {
				// and so on...
			}  		
		}  	
	}  
} 
But the problem is that, it will be very difficult to trace the code if there are too many range check due to the deep layer of nesting.
As a result, I have to write code like this to simulate the else if behavior:

Code: Select all

if a >= 0 && a < 10 { 
	logic a 
	goto END
	
} /*else*/ if a >= 10 && a < 20 { 
	logic b 
	goto END
	
} /*else*/ if a >= 20 && a < 30 { 
	logic c
	goto END
	
} /*else*/ if a >= 30 && a < 40 { 
	logic d
	goto END
	
} 
// ... and so on
END:
Although now it looks and works like an "else if" in the common C family languages and the nesting have been removed, goto is generally not a good idea in programming that might results in spaghetti code or hidden bugs if they are not handled properly.

Perhaps having else if, switch case, or some pattern matching for the future version of pixilang?
User avatar
NightRadio
Site Admin
Posts: 3944
Joined: Fri Jan 23, 2004 12:28 am
Location: Ekaterinburg. Russia
Contact:

Re: else if, switch case, or pattern matching?

Post by NightRadio »

i prefer the following way :)

Code: Select all

while 1 {
if a >= 0 && a < 10 { 
	logic a 
	break
} 
if a >= 10 && a < 20 { 
	logic b 
	break
}
if a >= 20 && a < 30 { 
	logic c
	break
}
if a >= 30 && a < 40 { 
	logic d
	break
}
break } 
User avatar
Logickin λ
Posts: 169
Joined: Sat Sep 08, 2018 8:31 pm
Contact:

Re: else if, switch case, or pattern matching?

Post by Logickin λ »

NightRadio wrote: Thu Apr 20, 2023 12:14 pm i prefer the following way :)

Code: Select all

while 1 {
if a >= 0 && a < 10 { 
	logic a 
	break
} 
if a >= 10 && a < 20 { 
	logic b 
	break
}
if a >= 20 && a < 30 { 
	logic c
	break
}
if a >= 30 && a < 40 { 
	logic d
	break
}
break } 
This is definitely an improvement from the goto method since the keyword break is common for switch case. I will used that as a work around for now. Thank you!
Post Reply