A Series on Sample Syntax for 25 Different Computer Programming Languages - Article 2
This is article 2 of 3 in my series of studying the syntax in 25 computer programming languages I’ve chosen. If you missed Article 1, please visit it here. Otherwise, here’s a brief summary of the languages I chose and what the syntax (code) examples are for each.
The List of Languages by Article
Article 1: Fortran
, COBOL
, Lisp
, BASIC
, Algol
, C
, Pascal
, Ada
[You are here] Article 2: Prolog
, Smalltalk
, C++
, Perl
, Python
, Ruby
, Java
, JavaScript
, PHP
Article 3: Swift
, Kotlin
, Go
, Rust
, Julia
, Dart
, TypeScript
, R
The Syntax Examples
“Hello World!”
If / Then / Else, or similar
Iteration over a collection of items, such as a list or an array
Defining and calling a function
I hope the work I’ve done here helps whoever may stumble upon it! And if I’ve made an error in the syntax I’ve shared, please leave a comment so that I can correct it!
Prolog
Prolog is a logic programming language that is primarily used in artificial intelligence and computational linguistics. In Prolog, programs are written as a series of logical statements, and the language is designed to allow efficient searching and pattern matching. Prolog is often used for tasks such as natural language processing, expert systems, and constraint solving.
Prolog was originally designed in France in the 1970s, and the name “Prolog” is actually an abbreviation of “PROgrammation en LOGique” (French for “programming in logic”). The language was later refined and popularized by researchers at the University of Edinburgh in Scotland.
Hello World!
:- initialization(main).
main :-
write('Hello World!'), nl,
halt.
If / Then / Else, or Similar
likes(john, mary).
likes(mary, chocolate).
?- likes(john, X), likes(mary, Y), X = Y.
X = chocolate,
Y = chocolate.
Iteration Over a Collection of Items, Such as a List or an Array
Prolog is a different type of language where “iteration” is typically accomplished using recursive rules rather than loops. In Prolog, you can define a recursive rule to iterate over a list and perform some operation on each element. For example, the following predicate sumlist/2 takes a list of integers as input and returns the sum of all the elements in the list:
sumlist([], 0). % Base case: sum of empty list is 0
sumlist([H|T], Sum) :-
sumlist(T, Rest), % Recurse on the tail of the list
Sum is H + Rest. % Add the head of the list to the sum of the rest
Then, to use this predicate, you can call it with a list as the first argument and a variable as the second argument as shown below.
?- sumlist([1, 2, 3, 4, 5], Sum).
Sum = 15.
Defining and Calling a Function
As mentioned above, Prolog is somewhat different than other programming languages due to its focus on logic. Functions are more of predicates that takes one or more inputs and produces one or more outputs. In the below example, we define and call a predicate that finds the maximum of two numbers.
max(X, Y, Max) :- X >= Y, Max = X.
max(X, Y, Max) :- X < Y, Max = Y.
Then, to use this predicate, we can call it with two numbers as the first two arguments and a variable as the third argument as shown below.
?- max(10, 20, Max).
Max = 20.
Smalltalk
Smalltalk is an object-oriented programming language that was developed in the 1970s and is still used today. Smalltalk was one of the first languages to fully embrace the concept of object-oriented programming, and it has been highly influential in the development of many other languages.
Smalltalk features a unique development environment known as the Smalltalk “image”, which allows programmers to modify the running system while it is still running. This makes it easy to experiment with code and to test changes in real time. Smalltalk is also known for its “live coding” capabilities, which allow developers to make changes to the system while it is still running without having to stop and restart.
A unique fact about Smalltalk is that it was originally developed by a team led by Alan Kay at Xerox PARC in the 1970s. The team that developed Smalltalk was also responsible for many other groundbreaking innovations, including the first graphical user interface and the first mouse. In fact, the Smalltalk environment was itself a key part of the development of these innovations, as it allowed programmers to experiment with new user interface ideas in real time.
Hello World!
Transcript show: 'Hello World!'.
If / Then / Else, or Similar
| x |
x := 5.
x > 3 ifTrue: [ Transcript show: 'x is greater than 3' ].
Iteration Over a Collection of Items, Such as a List or an Array
In Smalltalk, you can use the do: method to iterate over a collection and perform an operation on each element. For example, the following code iterates over an array of integers and prints each element
| anArray |
anArray := #(1 2 3 4 5).
anArray do: [ :each | Transcript show: each printString; cr ].
Defining and Calling a Function
In Smalltalk, methods are used instead of functions. A method is a block of code that is associated with a class, and it typically performs an action on an object or returns a value.
Object subclass: #MyClass
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Example'.
MyClass methodsFor: 'actions'!
myMethod
"Method body goes here"
! !
For example, the following code defines a method max:, which takes two numbers as arguments and returns the maximum.
Object subclass: #MathUtil
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Example'.
MathUtil methodsFor: 'comparisons'!
max: aNumber and: anotherNumber
^ aNumber > anotherNumber
ifTrue: [ aNumber ]
ifFalse: [ anotherNumber ]! !
When calling a method, we can then create an instance of MyClass and send the myMethod message to it to execute the method.
myInstance := MyClass new.
myInstance myMethod.
So in the example I method I provided that returns the maximum number between two numbers, we can send the ‘max:and:’ message to an instance of the ‘MathUtil’ class, as shown below.
| util |
util := MathUtil new.
util max: 10 and: 20.
C++
C++ is a popular general-purpose programming language that was developed as an extension of the C programming language. It was designed to add support for object-oriented programming, and it has become a common choice for building a wide variety of software, from operating systems to video games.
C++ supports many programming paradigms, including procedural, functional, and object-oriented programming. It is known for its efficiency, performance, and low-level access to computer resources. C++ has been standardized by the ISO, and its most recent version, C++20, was released in 2020.
A unique fact about C++ is that its name was originally a joke. The language was developed by Bjarne Stroustrup at Bell Labs in the early 1980s, and he originally called it “C with Classes.” The name “C++” was a play on the increment operator in C, and it was meant to suggest that the language was an improvement over C. However, Stroustrup initially used the name as a temporary placeholder and intended to come up with a better name later. The name stuck, however, and C++ has become one of the most widely used programming languages in the world.
Hello World!
#include <iostream>
int main() {
std::cout << "Hello World!\n";
return 0;
}
If / Then / Else, or Similar
#include <iostream>
int main() {
int x = 5;
if (x > 3) {
std::cout << "x is greater than 3\n";
}
return 0;
}
Iteration Over a Collection of Items, Such as a List or an Array
In C++, we can use a for loop to iterate over an array or a std::vector object, which is a dynamic array-like container provided by the C++ Standard Library. For example, the following code iterates over an array of integers and prints each element.
int arr[] = { 1, 2, 3, 4, 5 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < arr_size; i++) {
std::cout << arr[i] << std::endl;
}
I should also note that you can iterate over a ‘std::vector’ using a range-based ‘for’ loop, which will produce the same output as the example above.
std::vector<int> vec = { 1, 2, 3, 4, 5 };
for (int elem : vec) {
std::cout << elem << std::endl;
}
Defining and Calling a Function
In C++, we can define a function outside of the main code block, and then call it from within the main code block or from another function. For example, the following code defines a function max that takes two integers as arguments and returns the larger one:.
int max(int a, int b) {
return a > b ? a : b;
}
Then, we need to call the function. To do so, we use its name and pass in the desired arguments.
int result = max(10, 20);
std::cout << result << std::endl;
Perl
Perl is a high-level, general-purpose, interpreted programming language that was developed in the late 1980s. Perl has a syntax that is inspired by several other programming languages, including C, shell scripting, and sed. It is particularly well-suited for tasks involving text processing, such as parsing log files, extracting information from web pages, and automating system administration tasks.
Perl is that it was originally developed by Larry Wall as a scripting language for text processing, but it quickly became popular for a wide variety of tasks due to its flexibility and ease of use. The name “Perl” originally stood for “Practical Extraction and Report Language,” but it is now commonly known as the “Pathologically Eclectic Rubbish Lister,” a humorous nod to the fact that Perl allows programmers to take a variety of different approaches to solving problems.
Hello World!
print "Hello World!\n";
If / Then / Else, or Similar
my $x = 5;
if ($x > 3) {
print "x is greater than 3\n";
}
Iteration Over a Collection of Items, Such as a List or an Array
In Perl, we can use a foreach loop to iterate over a list or an array. For example, the following code iterates over an array of integers and prints each element.
my @arr = (1, 2, 3, 4, 5);
foreach my $elem (@arr) {
print $elem . "\n";
}
Using a ‘while’ loop with the ‘shift’ function will have the same result as above.
my @list = ("apple", "banana", "orange");
while (my $elem = shift @list) {
print $elem . "\n";
}
Defining and Calling a Function
In Perl, we can define a function using the sub keyword, and then call it from within the main code block or from another function. For example, the following code defines a function max that takes two numbers as arguments and returns the larger one.
sub max {
my ($a, $b) = @_;
return $a > $b ? $a : $b;
}
To call our function, we use its name and then pass in the desired arguments.
my $result = max(10, 20);
print $result . "\n";
Python
Python is a high-level, interpreted programming language that was first released in 1991. It emphasizes code readability and ease of use, with a focus on creating clean and efficient code. Python supports multiple programming paradigms, including object-oriented, imperative, and functional programming.
Python is actually named after the British comedy group Monty Python, and references to Monty Python are often used in examples and documentation for the language. In fact, the official tutorial for Python begins with a reference to Monty Python’s “Spam” sketch.
Hello World!
print("Hello World!")
If / Then / Else, or Similar
x = 5
if x > 3:
print("x is greater than 3")
Iteration Over a Collection of Items, Such as a List or an Array
In Python, we can use a for loop to iterate over a list or an array. For example, the following code iterates over a list of integers and prints each element.
lst = [1, 2, 3, 4, 5]
for elem in lst:
print(elem)
Similar to Perl, we can use a ‘while’ loop, but for Python we use the ‘pop’ method to iterate over a list in reverse order.
lst = ["apple", "banana", "orange"]
while lst:
elem = lst.pop()
print(elem)
Defining and Calling a Function
We can define a Python function using the def keyword, and then call it from within the main code block or from another function. For example, the following code defines a function max that takes two numbers as arguments and returns the larger one.
def max(a, b):
return a if a > b else b
To call our function, we use its name and pass in the desired arguments.
result = max(10, 20)
print(result)
Ruby
Ruby is a dynamic, interpreted, object-oriented programming language that was designed for programmer productivity and readability. It was first released in 1995 and has since gained popularity due to its clean and concise syntax, flexible programming style, and emphasis on code readability. Ruby is often used for web development, scripting, and rapid prototyping.
Ruby is that it has a feature called “monkey patching,” which allows developers to modify or add functionality to built-in classes and objects at runtime. This means that developers can extend the behavior of the language or third-party libraries without having to create new classes or objects from scratch. However, this feature can also lead to unpredictable behavior and can make debugging more difficult, so it is not always recommended to use it extensively.
Hello World!
puts "Hello World!"
If / Then / Else, or Similar
x = 5
if x > 3
puts "x is greater than 3"
end
Iteration Over a Collection of Items, Such as a List or an Array
In Ruby, you can use a for loop, a while loop, or an each method to iterate over a collection such as an array or a list. Below is an example using the each method.
array = [1, 2, 3, 4, 5]
array.each do |element|
puts element
end
Similarly, we can use the ‘reverse_each’ method to perform the same work in reverse order, as shown below.
array.reverse_each do |element|
puts element
end
Defining and Calling a Function
We can define a Ruby function using the def keyword, and then call it from within the main code block or from another function. For example, the following code defines a function max that takes two numbers as arguments and returns the larger one.
def max(a, b)
return a > b ? a : b
end
As with many other languages, we can call this function by using its name and passing in our desired arguments.
result = max(10, 20)
puts result
Java
Java is a popular high-level, object-oriented programming language originally developed by Sun Microsystems and now owned by Oracle. It is designed to be portable and can run on a variety of platforms. Java is known for its performance, security features, and robustness, making it a popular choice for building large-scale applications, such as enterprise systems, web applications, and mobile apps.
Java is that it was originally called “Oak” after the tree outside James Gosling’s office. The name was later changed to “Java” because the original name was already trademarked. The Java logo also features a stylized version of a coffee cup, a nod to Java’s popularity as a programming language for creating coffee-related applications.
Hello World!
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
If / Then / Else, or Similar
public class IfExample {
public static void main(String[] args) {
int x = 5;
if (x > 3) {
System.out.println("x is greater than 3");
}
}
}
Iteration Over a Collection of Items, Such as a List or an Array
In Java, we can use a for loop, a while loop, or a for-each loop to iterate over a collection such as an array or a list. Here is an example using a for-each loop.
int[] array = {1, 2, 3, 4, 5};
for (int element : array) {
System.out.println(element);
}
Or, if want to use a regular for loop to create the same output - we can do so.
int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Defining and Calling a Function
In Java, we can define a method as part of a class, and then call it from within the main code block or from another method. Methods are declared within classes, and can either be static (belonging to the class itself) or non-static (belonging to an instance of the class). For example, the following code defines a method max that takes two numbers as arguments and returns the larger one.
public static int max(int a, int b) {
return a > b ? a : b;
}
And of course, we call the method by using its name and passing in our desired arguments.
int result = max(10, 20);
System.out.println(result);
JavaScript
JavaScript is a high-level, interpreted programming language that is widely used for both client-side and server-side web development. It was initially created to make web pages interactive and is now used for creating full-fledged web applications and games, as well as in non-web environments like desktop and mobile app development.
JavaScript is that it was created by Brendan Eich in just 10 days in May 1995 while he was working at Netscape Communications Corporation. Initially, it was called Mocha, then it was renamed to LiveScript, and finally, it was renamed to JavaScript to capitalize on the popularity of Java at the time. The language was standardized as ECMAScript in 1997, and it has continued to evolve with regular updates to the specification.
Hello World!
console.log("Hello World!");
If / Then / Else, or Similar
let x = 5;
if (x > 3) {
console.log("x is greater than 3");
}
Iteration Over a Collection of Items, Such as a List or an Array
The below example demonstrates using a ‘for’ loop in JavaScript to iterate over an array.
let myArray = [1, 2, 3, 4, 5];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
Defining and Calling a Function
The below JavaScript code defines a function called sayHello that takes one argument, name, and logs a greeting to the console. The sayHello function is then called with the argument “Ira”, so the output will be “Hello, Ira!”.
function sayHello(name) {
console.log("Hello, " + name + "!");
}
sayHello("Ira");
PHP
PHP is a popular server-side scripting language that is designed for web development. It is an open-source language that is widely used to create dynamic web pages and web applications. PHP is typically used in conjunction with a web server such as Apache, and it can be embedded into HTML code or used as a standalone language.
PHP is that it was originally created in 1994 by Rasmus Lerdorf as a set of Common Gateway Interface (CGI) scripts to track visitors to his personal website. The acronym PHP originally stood for “Personal Home Page,” but it has since been rebranded as “Hypertext Preprocessor” to reflect its expanded capabilities as a general-purpose programming language.
Hello World!
<?php
echo "Hello World!";
?>
If / Then / Else, or Similar
<?php
$x = 5;
if ($x > 3) {
echo "x is greater than 3";
}
?>
Iteration Over a Collection of Items, Such as a List or an Array
The below code shows an example of a ‘foreach’ loop in PHP. First, we create an array $myArray with 10 elements. Then, we use the ‘foreach’ loop to iterate over the array and print each element to the screen.
$myArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($myArray as $value) {
echo $value . "\n";
}
Defining and Calling a Function
Here, we define a function called sayIntroduceMyself that takes one argument, $name, and prints a greeting to the screen. The function is then called with the argument “Ira”, so the output will be “Hello, my name is Ira!”
function sayIntroduceMyself($name) {
echo "Hello, my name is " . $name . "!";
}
sayIntroduceMyself("Ira");