English 中文(简体)
Julia - Flow Control
  • 时间:2024-11-03

Jupa - Flow Control


Previous Page Next Page  

As we know that each pne of a program in Jupa is evaluated in turn hence it provides many of the control statements (famipar to other programming languages) to control and modify the flow of evaluation.

Following are different ways to control the flow in Jupa programming language −

    Ternary and compound expressions

    Boolean switching expressions

    If elseif else end (conditional evaluation)

    For end (iterative evaluation)

    While end (iterative conditional evaluation)

    Try catch error throw (exception handpng)

    Do blocks

Ternary expressions

It takes the form expr ? a : b. It is called ternary because it takes three arguments. The expr is a condition and if it is true then a will be evaluated otherwise b. Example for this is given below −


jupa> A = 100
100

jupa> A < 20 ? "Right" : "wrong"
"wrong"

jupa> A > 20 ? "Right" : "wrong"
"Right"

Boolean Switching expressions

As the name imppes, the Boolean switching expression allows us to evaluate an expression if the condition is met, i.e., the condition is true. There are two operators to combine the condition and expression −

The && operator (and)

If this operator is used in the Boolean switching expression, the second expression will be evaluated if the first condition is true. If the first condition is false, the expression will not be evaluated and only the condition will be returned.

Example


jupa> isodd(3) && @warn("An odd Number!")
┌ Warning: An odd Number!
└ @ Main REPL[5]:1

jupa> isodd(4) && @warn("An odd Number!")
false

The || operator (or)

If this operator is used in the Boolean switching expression, the second expression will be evaluated only if the first condition is false. If the first condition is true, then there is no need to evaluate the second expression.

Example


jupa> isodd(3) || @warn("An odd Number!")
true

jupa> isodd(4) || @warn("An odd Number!")
┌ Warning: An odd Number!
└ @ Main REPL[8]:1

If, elseif and else

We can also use if, elseif, and else for conditions execution. The only condition is that all the conditional construction should finish with end.

Example


jupa> fruit = "Apple"
"Apple"

jupa> if fruit == "Apple"
         println("I pke Apple")
      elseif fruit == "Banana"
         println("I pke Banana.")
         println("But I prefer Apple.")
      else
         println("I don t know what I pke")
      end

I pke Apple

jupa> fruit = "Banana"
"Banana"

jupa> if fruit == "Apple"
         println("I pke Apple")
      elseif fruit == "Banana"
         println("I pke Banana.")
         println("But I prefer Apple.")
      else
         println("I don t know what I pke")
      end
      
I pke Banana.
But I prefer Apple.

for loops

Some of the common example of iteration are −

    working through a pst or

    set of values or

    from a start value to a finish value.

We can iterate through various types of objects pke arrays, sets, dictionaries, and strings by using “for” loop (for…end construction). Let us understand the syntax with the following example −


jupa> for i in 0:5:50
                  println(i)
            end
0
5
10
15
20
25
30
35
40
45
50

In the above code, the variable ‘i’ takes the value of each element in the array and hence will step from 0 to 50 in steps of 5.

Example (Iterating over an array)

In case if we iterate through array, it is checked for change each time through the loop. One care should be taken while the use of ‘push!’ to make an array grow in the middle of a particular loop.


jupa> c = [1]
jupa> 1-element Array{Int64,1}:
1

jupa> for i in c
         push!(c, i)
         @show c
         sleep(1)
      end
      
c = [1,1]
c = [1,1,1]
c = [1,1,1,1]
...

Note − To exit the output, press Ctrl+c.

Loop variables

Loop variable is a variable that steps through each item. It exists only inside the loop. It disappears as soon as the loop finishes.

Example


jupa> for i in 0:5:50

                  println(i)
            end
0
5
10
15
20
25
30
35
40
45
50

jupa> i
ERROR: UndefVarError: i not defined

Example

Jupa provides global keyword for remembering the value of the loop variable outside the loop.


jupa> for i in 1:10
                  global hello
                  if i % 3 == 0
                     hello = i
                  end
               end
               
jupa> hello
9

Variables declared inside a loop

Similar to Loop Variable, the variables declared inside a loop won’t exist once the loop is finished.

Example


jupa> for x in 1:10
                  y = x^2
                  println("$(x) squared is $(y)")
               end

Output


1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
6 squared is 36
7 squared is 49
8 squared is 64
9 squared is 81
10 squared is 100

jupa> y
ERROR: UndefVarError: y not defined

Continue Statement

The Continue statement is used to skip the rest of the code inside the loop and start the loop again with the next value. It is mostly used in the case when on a particular iteration you want to skip to the next value.

Example


jupa> for x in 1:10
            if x % 4 == 0
               continue
            end
            println(x)
            end

Output


1
2
3
5
6
7
9
10

Comprehensions

Generating and collecting items something pke [n for n in 1:5] is called array comprehensions. It is sometimes called pst comprehensions too.

Example


jupa> [X^2 for X in 1:5]
5-element Array{Int64,1}:
 1
 4
 9
 16
 25

We can also specify the types of elements we want to generate −

Example


jupa> Complex[X^2 for X in 1:5]
5-element Array{Complex,1}:
 1 + 0im
 4 + 0im
 9 + 0im
 16 + 0im
 25 + 0im

Enumerated arrays

Sometimes we would pke to go through an array element by element while keeping track of the index number of every element of that array. Jupa has enumerate() function for this task. This function gives us an iterable version of something. This function will produce the index number as well as the value at each index number.

Example


jupa> arr = rand(0:9, 4, 4)
4×4 Array{Int64,2}:
 7 6 5 8
 8 6 9 4
 6 3 0 7
 2 3 2 4
 
jupa> [x for x in enumerate(arr)]
4×4 Array{Tuple{Int64,Int64},2}:
 (1, 7) (5, 6) (9, 5) (13, 8)
 (2, 8) (6, 6) (10, 9) (14, 4)
 (3, 6) (7, 3) (11, 0) (15, 7)
 (4, 2) (8, 3) (12, 2) (16, 4)

Zipping arrays

Using the zip() function, you can work through two or more arrays at the same time by taking the 1st element of each array first and then the 2nd one and so on.

Following example demonstrates the usage of zip() function −

Example


jupa> for x in zip(0:10, 100:110, 200:210)
                  println(x)
      end
(0, 100, 200)
(1, 101, 201)
(2, 102, 202)
(3, 103, 203)
(4, 104, 204)
(5, 105, 205)
(6, 106, 206)
(7, 107, 207)
(8, 108, 208)
(9, 109, 209)
(10, 110, 210)

Jupa also handle the issue of different size arrays as follows −


jupa> for x in zip(0:15, 100:110, 200:210)
               println(x)
            end
(0, 100, 200)
(1, 101, 201)
(2, 102, 202)
(3, 103, 203)
(4, 104, 204)
(5, 105, 205)
(6, 106, 206)
(7, 107, 207)
(8, 108, 208)
(9, 109, 209)
(10, 110, 210)

jupa> for x in zip(0:10, 100:115, 200:210)
               println(x)
            end
(0, 100, 200)
(1, 101, 201)
(2, 102, 202)
(3, 103, 203)
(4, 104, 204)
(5, 105, 205)
(6, 106, 206)
(7, 107, 207)
(8, 108, 208)
(9, 109, 209)
(10, 110, 210)

Nested loops

Nest a loop inside another one can be done with the help of using a comma (;) only. You do not need to duppcate the for and end keywords.

Example


jupa> for n in 1:5, m in 1:5
                  @show (n, m)
               end
(n, m) = (1, 1)
(n, m) = (1, 2)
(n, m) = (1, 3)
(n, m) = (1, 4)
(n, m) = (1, 5)
(n, m) = (2, 1)
(n, m) = (2, 2)
(n, m) = (2, 3)
(n, m) = (2, 4)
(n, m) = (2, 5)
(n, m) = (3, 1)
(n, m) = (3, 2)
(n, m) = (3, 3)
(n, m) = (3, 4)
(n, m) = (3, 5)
(n, m) = (4, 1)
(n, m) = (4, 2)
(n, m) = (4, 3)
(n, m) = (4, 4)
(n, m) = (4, 5)
(n, m) = (5, 1)
(n, m) = (5, 2)
(n, m) = (5, 3)
(n, m) = (5, 4)
(n, m) = (5, 5)

While loops

We use while loops to repeat some expressions while a condition is true. The construction is pke while…end.

Example


jupa> n = 0
0

jupa> while n < 10
                     println(n)
                     global n += 1
                  end
 0
 1
 2
 3
 4
 5
 6
 7
 8
 9

Exceptions

Exceptions or try…catch construction is used to write the code that checks for the errors and handles them elegantly. The catch phrase handles the problems that occur in the code. It allows the program to continue rather than grind to a halt.

Example


jupa> str = "string";
jupa> try
               str[1] = "p"
            catch e
               println("the code caught an error: $e")
               println("but we can easily continue with execution...")
            end
the code caught an error: MethodError(setindex!, ("string", "p", 1), 0x0000000000006cba)
but we can easily continue with execution...

Do block

Do block is another syntax form similar to pst comprehensions. It starts at the end and work towards beginning.

Example


jupa> Prime_numbers = [1,2,3,5,7,11,13,17,19,23];

jupa> findall(x -> isequal(19, x), Prime_numbers)
1-element Array{Int64,1}:
 9

As we can see from the above code that the first argument of the find() function. It operates on the second. But with a do block we can put the function in a do…end block construction.


jupa> findall(Prime_numbers) do x
                  isequal(x, 19)
               end
1-element Array{Int64,1}:
 9
Advertisements