Wiki

root/cobra/trunk/HowTo/130-MakeABranchStatement.cobra

Revision 2335, 1.7 KB (checked in by Chuck.Esterbrook, 2 years ago)

Improvements to the How-To's.

  • Property svn:eol-style set to native
Line 
1"""
2MakeABranchStatement.cobra
3
4General syntax:
5
6    branch WHAT
7        on VALUE1
8            STATEMENTS1
9        on VALUE2
10            STATEMENTS2
11        [else
12            STATEMENTS]
13
14    branch WHAT
15        on VALUE1, STATEMENT1
16        on VALUE2, STATEMENT2
17        [else, STATEMENT]
18
19Key rules of the branch statement:
20
21    * What's being branched on must be an integer, character, enumeration or string.
22
23    * The expressions being matched must be constants (ex: 0, 1, 'x', State.Off, "foo").
24
25When a branch statement isn't feasible, you can possibly:
26
27    * Make a class hierarchy and send a message to the object.
28
29    * Use an `if-else` ladder (see MakeAnIfElseLadder.cobra)
30
31
32See also: MakeAnIfElseLadder.cobra, CheckInheritanceAndImplementation.cobra.
33"""
34
35
36class Program
37
38    def main
39
40        word = ''
41
42        # This is the general syntax, below. Notice the keywords `branch` and
43        # `on` as well as the indentation under each `on` part:
44        x = 2
45        branch x
46            on 1
47                isEven = false
48                word = 'one'
49            on 2
50                isEven = true
51                word = 'two'
52            on 3
53                isEven = false
54                word = 'three'
55        assert isEven
56        assert word == 'two'
57
58        # In addition to `on`, you can put an `else` at the end:
59        x = 2
60        branch x
61            on 1
62                word = 'one'
63            on 3
64                word = 'three'
65            else
66                word = 'else'
67        assert word == 'else'
68
69        # If there is only one statement for the `on` or `else` and you want to
70        # tighten up your code, you can do so by using a colon (,) and putting the
71        # statement on the same line, like so:
72        x = 2
73        branch x
74            on 1, word = 'one'
75            on 3, word = 'three'
76            else, word = 'else'
77        assert word == 'else'
78
79        # You can have more than one value for `on`:
80        x = 2
81        branch x
82            on 1 or 2 or 3, word = 'number'
83            else, word = 'else'
84        assert word == 'number'
85
86        # You can also branch on enumerations, strings and characters.
Note: See TracBrowser for help on using the browser.