🔍
Patterns
O has a pattern matching feature. Its principle is similar to the "switch" construction in C language, but pattern matching in O is more powerful since it allows matching against all types, including lists, vectors and their parts (e.g. destructuring). Usually, pattern matching is used to construct various types according to input constraints.
o)m:{match [x;y] { (1 2 3;4 5 6) -> "888"; (`a`s`d!1 2 3;_) -> `a`s`d; (12;_) -> 10#3; _ -> 777 } };
o)m[1 2 3;0]
777
o)m[(1 2 3;4 5 6);0]
777
o)m[1 2 3;4 5 6]
"888"
o)m[12;3]
3 3 3 3 3 3 3 3 3 3
o)
In scripts you can write match
more readble:
m:{match [x;y] {
(1 2 3;4 5 6) -> "888";
(`a`s`d!1 2 3;_) -> `a`s`d;
(12;_) -> 10#3;
_ -> 777
} };
show m[1 2 3;4 5 6];
"888"
Be careful if you pass a list to a match: it may turn into a vector after evaluation. Use the
pick
to avoid problems. o)a:1;
o)b:`c;
o)m:{match [x] { (1; _) -> "start with one"; _ -> type x }};
o)m (a;b)
"start with one"
o)b:2; m (a;b)
`v`long
o)m:{match [x] { pick[1; _] -> "start with one"; _ -> type x }};
o)m pick[a;b]
"start with one"
o)