Iteration and recursion (C, Java, python, Clojure)
The repetition function is one of the most basic functions in a programming language, and is one element of the three functions of a structured language described in the history of programming languages: (1) sequential progression, (2) conditional branching, and (3) repetition.
This is expressed, for example, in the C language as follows.
int main()
{
int i;
for(i = 0; i < 3; i++){
printf("%d ", i);
}
printf("n");
return 0;
}
And in Java, it looks like this
class Test{
public static void main(String args[]){
for(int i = 0; i < 3; i++)
System.out.printf("%d ",i);
System.out.printf("n");
}
}
In Javascript, it would look like this
putstr(i + " ");
}
print("")
for(var i = 1; i < 10; i+=2){ /*増分(ステップ)=2*/
putstr(i + " ");
}
print("")
In python, this is a fairly simple form.
for i in range(0,3):
print i,
print
In Clojure, the expression is a continuation of the sequence and looks like this
(doseq [i (range 0 3)]
(println i))
The latter two (python and Clojure) are improved in terms of shortness of code and ease of intuitive understanding.
In Clojure, there are other iterations besides “doseq”, such as for, loop~recur, map, reduce, and so on.
First of all, there is map, which is the simplest and most used one.
(map + [1 2 3] [4 5 6])
;;=> (5 7 9)
In map, the function (“+” in the above case) is applied to each vector (or map data, etc.) in turn. If you want to apply these functions in a round-robin fashion, you can use for as follows.
(def digits [1 2 3])
(for [x1 digits
x2 digits]
(* x1 x2))
;;=> (1 2 3 2 4 6 3 6 9)
In addition, loop~recur is used in recursive syntax and can be expressed in its simplest form as follows.
(loop [x 10 ;;カウント初期値
sv. f(0)]
(when (> x 1)
(println x)
(do (println x). ;; デバッグ用のデータ出力
(recur (- x 2)(f sv x))))
The above is a function that recurs at the end for a variable x, and exits the loop when a certain condition (x>1) is met. recur variables must all appear as defined in the loop, and in order to monitor (debug) what is happening inside, the recur and debug function with do. Here, the variable f(x)=sv changes recursively.
As for map, it is a higher-order function (a function that evaluates a function), and is used as a characteristic of functional languages. I would like to discuss these higher-order functions separately.
コメント