Re: SWITCH question
- Posted by jimcbrown (admin) Jan 05, 2018
- 2443 views
More problems with the switch statement:
Example 2
include std/stack.e atom op = stack:new(FIFO) ? op atom stk = op ? stk switch stk do case op then -- err line has moved puts(1, "\n result is first stack \n" ) case else puts(1, "\n result is something else \n") end switch
/home/irv/stk.ex:10
<0091>:: found variable but expected 'else', an atom, string, constant or enum
case op then
Notice, please, that this second version has two problems:
- It did not print the two 1s, unlike the first program
the second is in an earlier step (parsing?).
That's correct. You are getting a parse-time error, so that's why nothing was printed - no code had been executed yet at this point.
- Secondly, what does that error message even mean????
The value in a case statement must be a constant - variables aren't allowed.
I asked Jeremy about this once and he said by restricting it to constants we could optimize and make switch faster than if-else. He pointed out that this is also how the statement works in C.
Example 3
atom stk = 1 ? stk atom op = stk ? op switch stk do case op then -- err here again puts(1, "\n result is first stack \n" ) case else puts(1, "\n result is something else \n") end switch
/home/irv/stk.ex:8
<0091>:: found variable but expected 'else',an atom, string, constant or enum
case op then
Am I misunderstanding something? I could swear that everything in there was atoms!
op is a variable whose value can change, not a fixed constant whose value is known at parse-time.