<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[AQ Developer Blog]]></title><description><![CDATA[AQ Official Developer Blog.
Github: https://github.com/aq-org/AQ
Official Website: https://www.axa6.com
Email: xie.zicong@axa6.com]]></description><link>https://blog.axa6.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1738475024420/377428fe-b29b-4af4-9758-dc56597ce007.png</url><title>AQ Developer Blog</title><link>https://blog.axa6.com</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 17 Apr 2026 11:38:21 GMT</lastBuildDate><atom:link href="https://blog.axa6.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[模块导入功能设计草稿]]></title><description><![CDATA[模块以Java类似的方式实现导入（全限定名实现），删除原有字节码单独的设计内容。
仍然使用绝对或相对路径的字符串作为导入的第一个参数，第二个参数不可省略，为模块别名。
目前已经实现了模块导入的部分功能，但由于部分设计问题，存在较多错误。
from-import延迟实现。
在HandleImport时创建一个新的类，名称为”~导入路径~.!__start”。其它类处理同样参见这个操作，类名均改为”~导入路径~.类”。但是在处理类的创建时（各种HandleVarDecl及类似函数），应当加入类型处理...]]></description><link>https://blog.axa6.com/5qih5z2x5a85ywl5yqf6io96k66k6h6i2j56i</link><guid isPermaLink="true">https://blog.axa6.com/5qih5z2x5a85ywl5yqf6io96k66k6h6i2j56i</guid><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Sat, 26 Apr 2025 12:43:05 GMT</pubDate><content:encoded><![CDATA[<p>模块以Java类似的方式实现导入（全限定名实现），删除原有字节码单独的设计内容。</p>
<p>仍然使用绝对或相对路径的字符串作为导入的第一个参数，第二个参数不可省略，为模块别名。</p>
<p>目前已经实现了模块导入的部分功能，但由于部分设计问题，存在较多错误。</p>
<p>from-import延迟实现。</p>
<p>在HandleImport时创建一个新的类，名称为”~导入路径~.!__start”。其它类处理同样参见这个操作，类名均改为”~导入路径~.类”。但是在处理类的创建时（各种HandleVarDecl及类似函数），应当加入类型处理模块。对于存在导入模块的类创建应当通过模块导入表获取实际创建内容。</p>
<p>虚拟机的处理中注释原有废弃逻辑。重新对NEW等进行设计，加入对于名称的处理逻辑。在此处应当注意的是，应当对名称解析进行判断，读取“~导入路径~“并进行相关操作。但是直接进行该类操作会造成导入模块的NEW功能失效。无法正确对导入字节码的文件进行处理，同时可能会造成错误创建的行为发生（导入模块的类与原始类发生冲突时）。</p>
<p>应对原有结构进行改写。</p>
]]></content:encoded></item><item><title><![CDATA[Aq语言语法设计文档]]></title><description><![CDATA[概览
为满足AQ语言持续发展，提升AQ语言在软件开发的便捷性和高效性，提升AQ语言长期持续有效发展，推进AQ v0.2.0 版本更快面向市场发布，决定对AQ语言的语法进行规范。
其详细的语法参照市面上常见的编程语言，总结其共有特点，对语言语法进行简化，同时完善部分语言的历史性问题，在语法上进行优化，降低学习难度和成本。
注释
注释参照C/C++等C-style语言的设计，采用两种注释方式。
// 单行注释
/*多
  行
  注
  释*/

运算符
基本采取和主流语言一致（参照C/C++），部...]]></description><link>https://blog.axa6.com/aq-language-syntax-design-documentation</link><guid isPermaLink="true">https://blog.axa6.com/aq-language-syntax-design-documentation</guid><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Thu, 20 Mar 2025 14:02:13 GMT</pubDate><content:encoded><![CDATA[<h1 id="heading-5qac6kei">概览</h1>
<p>为满足AQ语言持续发展，提升AQ语言在软件开发的便捷性和高效性，提升AQ语言长期持续有效发展，推进AQ v0.2.0 版本更快面向市场发布，决定对AQ语言的语法进行规范。</p>
<p>其详细的语法参照市面上常见的编程语言，总结其共有特点，对语言语法进行简化，同时完善部分语言的历史性问题，在语法上进行优化，降低学习难度和成本。</p>
<h1 id="heading-5roo6yek">注释</h1>
<p>注释参照C/C++等C-style语言的设计，采用两种注释方式。</p>
<pre><code class="lang-c"><span class="hljs-comment">// 单行注释</span>
<span class="hljs-comment">/*多
  行
  注
  释*/</span>
</code></pre>
<h1 id="heading-6lq566x56ym">运算符</h1>
<p>基本采取和主流语言一致（参照C/C++），部分特殊处理。</p>
<pre><code class="lang-python">原生类型（参照Python和Java）
有none对象
byte（bool和char类型）为<span class="hljs-number">1</span>字节
int和long同长为<span class="hljs-number">8</span>字节
float和double同长为<span class="hljs-number">8</span>字节

字符串（参照Python）
字符串是原始类型
可以直接操作字符串进行加法
<span class="hljs-string">"字符串1"</span> + <span class="hljs-string">"字符串2"</span> == <span class="hljs-string">"字符串1字符串2"</span>

不同的字符串样式（参照Python）
<span class="hljs-string">'字符串样式1'</span>
<span class="hljs-string">"字符串样式2"</span>
</code></pre>
<h1 id="heading-5yy6yep">变量</h1>
<p>参照Python和JavaScript，包含C/C++语法。</p>
<pre><code class="lang-javascript">变量声明或变量定义
形式<span class="hljs-number">1</span>（参照JavaScript）
<span class="hljs-keyword">var</span> 变量名;
<span class="hljs-keyword">var</span> 变量名 = 变量值;

形式<span class="hljs-number">2</span>（auto关键字等效于<span class="hljs-keyword">var</span>关键字）
auto 变量名;
auto 变量名 = 变量值;

形式<span class="hljs-number">3</span>（参照Python）
变量名;
变量名 = 变量值;

形式<span class="hljs-number">4</span>（参照C/C++）
int 变量名;
int 变量名 = 变量值;
</code></pre>
<h1 id="heading-5rwb56il5o6n5yi2">流程控制</h1>
<p>基本采取和主流语言一致（参照C/C++），部分特殊处理。</p>
<pre><code class="lang-cpp">判断语句<span class="hljs-number">1</span>（参照C/C++）
<span class="hljs-keyword">if</span> (条件<span class="hljs-number">1</span>) {
符合条件<span class="hljs-number">1</span>执行的代码
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (条件<span class="hljs-number">2</span>) {
不符合条件<span class="hljs-number">1</span>符合条件<span class="hljs-number">2</span>执行的代码（可省略）
} <span class="hljs-keyword">else</span> {
全部不符合执行的代码（可省略）
}

判断语句<span class="hljs-number">2</span>（参照C/C++）
<span class="hljs-keyword">if</span> (条件) 运行代码（仅适用于一行运行代码的情况）

重复语句<span class="hljs-number">1</span>（参照C/C++）
<span class="hljs-keyword">while</span> (重复条件) {
符合重复条件运行的代码
}

重复语句<span class="hljs-number">2</span>（参照C/C++）
<span class="hljs-keyword">while</span> (重复条件) 运行代码（仅适用于一行运行代码的情况）

重复语句<span class="hljs-number">3</span>（参照C/C++）
<span class="hljs-keyword">for</span> ( 开始时运行代码 ; 重复条件 ; 运行后运行代码 ) {
符合重复条件运行的代码
}
</code></pre>
<h1 id="heading-5ye95pww">函数</h1>
<p>基本采取和主流语言一致（参照C/C++），部分特殊处理。</p>
<pre><code class="lang-cpp">均无函数声明

普通函数
函数定义<span class="hljs-number">1</span>（参照C/C++）
返回类型 函数名称 (参数<span class="hljs-number">1</span>（均为变量定义）, 参数<span class="hljs-number">2</span>, 参数<span class="hljs-number">3</span>（均可省略）) {
运行代码
<span class="hljs-keyword">return</span> 返回值;
}

函数定义<span class="hljs-number">2</span>（动态类型，参照JavaScript）
<span class="hljs-keyword">auto</span> 函数名称 (参数<span class="hljs-number">1</span>（均为变量定义）, 参数<span class="hljs-number">2</span>，参数<span class="hljs-number">3</span>（均可省略）) {
运行代码
<span class="hljs-keyword">return</span> 返回值;
}
var 函数名称 (参数<span class="hljs-number">1</span>（均为变量定义）, 参数<span class="hljs-number">2</span>, 参数<span class="hljs-number">3</span>（均可省略）) {
运行代码
<span class="hljs-keyword">return</span> 返回值;
}

多返回值函数（参照Go）
函数定义
func 函数名称 (参数<span class="hljs-number">1</span>（均为变量定义）, 参数<span class="hljs-number">2</span>, 参数<span class="hljs-number">3</span>（均可省略）) (返回变量<span class="hljs-number">1</span>（均为变量定义）, 返回变量<span class="hljs-number">2</span>（均可省略）) {
运行代码
<span class="hljs-keyword">return</span> 返回值<span class="hljs-number">1</span>, 返回值<span class="hljs-number">2</span>;
}
</code></pre>
<h1 id="heading-5qih5z2x">模块</h1>
<p>参照Python、JavaScript等语言</p>
<pre><code class="lang-python">导入模块
<span class="hljs-keyword">import</span> 模块名称

从模块导入特定函数
<span class="hljs-keyword">from</span> 模块名称 <span class="hljs-keyword">import</span> 函数名称<span class="hljs-number">1</span>，函数名称<span class="hljs-number">2</span>（可省略）

从模块导入所有函数
<span class="hljs-keyword">from</span> 模块名称 <span class="hljs-keyword">import</span> *

模块设置别名
<span class="hljs-keyword">import</span> 模块名称 <span class="hljs-keyword">as</span> 别名
</code></pre>
<h1 id="heading-57g7">类</h1>
<p>参照C/C++、Python和JavaScript，有修改。</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">class</span> 类名称 {</span>
构造函数
类名称(参数<span class="hljs-number">1</span>, 参数<span class="hljs-number">2</span>（均可省略）) {
构造函数代码
}（可省略）

无析构函数

其它函数或变量定义

}

<span class="hljs-class"><span class="hljs-keyword">class</span> 类名称 <span class="hljs-title">extends</span> 父类名称 {</span>
构造函数
类名称(参数<span class="hljs-number">1</span>, 参数<span class="hljs-number">2</span>（均可省略）) {
构造函数代码
}（可省略）

无析构函数

其它函数或变量定义

}
</code></pre>
<p>未完待续……</p>
]]></content:encoded></item><item><title><![CDATA[有关Python语言语法的研究报告]]></title><description><![CDATA[AQ语言语法设计参考文档
概述
根据TIOBE Index的最新报告显示，Python位于榜单第一名，其市占率达23.85%，同比上月增加8.22%。
摘自TIOBE Index的一些信息：
Some information about Python:
 Highest Position (since 2001): #1 in Mar 2025

 Lowest Position (since 2001): #13 in Feb 2003

 Language of the Year: 2007...]]></description><link>https://blog.axa6.com/python</link><guid isPermaLink="true">https://blog.axa6.com/python</guid><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Thu, 20 Mar 2025 12:45:34 GMT</pubDate><content:encoded><![CDATA[<p><em>AQ语言语法设计参考文档</em></p>
<h1 id="heading-5qac6lw">概述</h1>
<p>根据<a target="_blank" href="https://www.tiobe.com/">TIOBE Index</a>的最新报告显示，Python位于榜单第一名，其市占率达23.85%，同比上月增加8.22%。</p>
<p>摘自<a target="_blank" href="https://www.tiobe.com/">TIOBE Index</a>的一些信息：</p>
<h4 id="heading-some-information-about-python"><strong>Some information about Python:</strong></h4>
<pre><code class="lang-plaintext"> Highest Position (since 2001): #1 in Mar 2025
</code></pre>
<pre><code class="lang-plaintext"> Lowest Position (since 2001): #13 in Feb 2003
</code></pre>
<pre><code class="lang-plaintext"> Language of the Year: 2007, 2010, 2018, 2020, 2021, 2024
</code></pre>
<p>近十年来，Python市占率一路走高，在各类编程语言中发挥的作用不断加强，自2020年后以来的AI热潮推动了Python语言的进一步发展。部分成功的原因有：简单的语法对于非专业人员的开发极为有利，可以快速实现对于需求的设计和更多其它语言实现需要较为复杂的技术。相较于AI的高性能需求，Python并未能发挥其特点。作为解释性语言，其主要实现CPython中完全采用解释器虚拟机设计，没有JIT（即时编译，Just-In Time）支持，因此相较于同类语言有较大的弊端。但其完备的社区资源和第三方库（C/C++支持）弥补了该缺陷。对于其更多的成功原因不再过多分析，本报告将主要着眼于其语法设计的特点，进行针对性的分析。</p>
<p>删除了部分编程语言相同语法。</p>
<h1 id="heading-5roo6yek">注释</h1>
<pre><code class="lang-plaintext"># 用井字符开头的是单行注释

""" 多行字符串用三个引号
    包裹，也常被用来做多
    行注释
"""
</code></pre>
<h1 id="heading-5y6f5ael5pww5o2u57g75z6l5zkm6lq566x56ym">原始数据类型和运算符</h1>
<pre><code class="lang-plaintext"># 除法自动转换成浮点数
35 / 5  # =&gt; 7.0
10.0 / 3  # =&gt; 3.3333333333333335

# 整数除法的结果都是向下取整
5 // 3       # =&gt; 1
5.0 // 3.0   # =&gt; 1.0 # 浮点数也可以
-5 // 3      # =&gt; -2
-5.0 // 3.0  # =&gt; -2.0

# 模除
7 % 3 # =&gt; 1
# i % j 结果的正负符号会和 j 相同，而不是和 i 相同
-7 % 3 # =&gt; 2

# x 的 y 次方
2**4 # =&gt; 16

# 布尔值 (注意: 首字母大写)
True   # =&gt; True
False  # =&gt; False

# 用 not 取非
not True   # =&gt; False
not False  # =&gt; True


# 使用布尔逻辑运算符对数字类型的值进行运算时，会把数值强制转换为布尔值进行运算
# 但计算结果会返回它们的强制转换前的值
# 注意不要把 bool(ints) 与位运算的 "按位与"、"按位或" (&amp;, |) 混淆
bool(0)     # =&gt; False
bool(4)     # =&gt; True
bool(-6)    # =&gt; True
0 and 2     # =&gt; 0
-5 or 0     # =&gt; -5

# 大小比较可以连起来！
1 &lt; 2 &lt; 3  # =&gt; True
2 &lt; 3 &lt; 2  # =&gt; False

# (is 对比 ==) is 判断两个变量是否引用同一个对象,
# 而 == 判断两个对象是否含有相同的值
a = [1, 2, 3, 4]  # 变量 a 是一个新的列表, [1, 2, 3, 4]
b = a             # 变量 b 赋值了变量 a 的值
b is a            # =&gt; True, a 和 b 引用的是同一个对象
b == a            # =&gt; True, a 和 b 的对象的值相同
b = [1, 2, 3, 4]  # 变量 b 赋值了一个新的列表, [1, 2, 3, 4]
b is a            # =&gt; False, a 和 b 引用的不是同一个对象
b == a            # =&gt; True, a 和 b 的对象的值相同

# 创建字符串可以使用单引号（'）或者双引号（"）
"这是个字符串"
'这也是个字符串'

# 字符串可以使用加号连接成新的字符串
"Hello " + "world!"  # =&gt; "Hello world!"
# 非变量形式的字符串甚至可以在没有加号的情况下连接
"Hello " "world!"    # =&gt; "Hello world!"

# 字符串可以被当作字符列表
"Hello world!"[0]  # =&gt; 'H'

# 你可以获得字符串的长度
len("This is a string")  # =&gt; 16

# 你可以使用 f-strings 格式化字符串（python3.6+）
name = "Reiko"
f"She said her name is {name}." # =&gt; "She said her name is Reiko"
# 你可以在大括号内几乎加入任何 python 表达式，表达式的结果会以字符串的形式返回
f"{name} is {len(name)} characters long." # =&gt; "Reiko is 5 characters long."

# 用 .format 来格式化字符串
"{} can be {}".format("strings", "interpolated")
# 可以重复参数以节省时间
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
# =&gt; "Jack be nimble, Jack be quick, Jack jump over the candle stick"
# 如果不想数参数，可以用关键字
"{name} wants to eat {food}".format(name="Bob", food="lasagna") 
# =&gt; "Bob wants to eat lasagna"

# 如果你的 Python3 程序也要在 Python2.5 以下环境运行，也可以用老式的格式化语法
"%s can be %s the %s way" % ("strings", "interpolated", "old")

# None是一个对象
None  # =&gt; None

# 当与 None 进行比较时不要用 ==，要用 is。is 是用来比较两个变量是否指向同一个对象。
"etc" is None  # =&gt; False
None is None  # =&gt; True

# None，0，空字符串，空列表，空字典，空元组都算是 False
# 所有其他值都是 True
bool(0)  # =&gt; False
bool("")  # =&gt; False
bool([]) # =&gt; False
bool({}) # =&gt; False
bool(()) # =&gt; False
</code></pre>
<h1 id="heading-5yy6yep5zkm6zug5zci">变量和集合</h1>
<pre><code class="lang-plaintext"># print是内置的打印函数
print("I'm Python. Nice to meet you!")

# 默认情况下，print 函数会在输出结果后加入一个空行作为结尾
# 可以使用附加参数改变输出结尾
print("Hello, World", end="!")  # =&gt; Hello, World!

# 可以很简单的从终端获得输入数据
input_string_var = input("Enter some data: ") # 返回字符串数值

# 在给变量赋值前不用提前声明
# 习惯上变量命名是小写，用下划线分隔单词
some_var = 5
some_var  # =&gt; 5

# 访问未赋值的变量会抛出异常
# 参考流程控制一段来学习异常处理
some_unknown_var  # 抛出 NameError

# "if" 可以用作表达式，它的作用等同于 C 语言的三元运算符 "?:"
"yay!" if 0 &gt; 1 else "nay!"  # =&gt; "nay!"

# 用列表 (list) 储存序列
li = []
# 创建列表时也可以同时赋给元素
other_li = [4, 5, 6]

# 用append在列表最后追加元素
li.append(1)    # li现在是[1]
li.append(2)    # li现在是[1, 2]
li.append(4)    # li现在是[1, 2, 4]
li.append(3)    # li现在是[1, 2, 4, 3]
# 用pop从列表尾部删除
li.pop()        # =&gt; 3 且li现在是[1, 2, 4]
# 把3再放回去
li.append(3)    # li变回[1, 2, 4, 3]

# 列表存取跟数组一样
li[0]  # =&gt; 1
# 取出最后一个元素
li[-1]  # =&gt; 3

# 越界存取会造成 IndexError
li[4]  # 抛出 IndexError

# 列表有切割语法
li[1:3]    # =&gt; [2, 4]
# 取尾
li[2:]     # =&gt; [4, 3]
# 取头
li[:3]     # =&gt; [1, 2, 4]
# 隔一个取一个
li[::2]    # =&gt;[1, 4]
# 倒排列表
li[::-1]   # =&gt; [3, 4, 2, 1]
# 可以用三个参数的任何组合来构建切割
# li[始:终:步伐]

# 简单的实现了单层数组的深度复制
li2 = li[:]  # =&gt; li2 = [1, 2, 4, 3] ，但 (li2 is li) 会返回 False

# 用 del 删除任何一个元素
del li[2]   # li 现在为 [1, 2, 3]

# 删除第一个匹配的元素
li.remove(2)  # li 现在为 [1, 3]
li.remove(2)  # 抛出错误 ValueError: 2 is not in the list

# 在指定索引处插入一个新的元素
li.insert(1, 2)  # li is now [1, 2, 3] again

# 获得列表第一个匹配的值的索引
li.index(2)  # =&gt; 1
li.index(4)  # 抛出一个 ValueError: 4 is not in the list

# 列表可以相加
# 注意：li 和 other_li 的值都不变
li + other_li   # =&gt; [1, 2, 3, 4, 5, 6]

# 用 "extend()" 拼接列表
li.extend(other_li)   # li 现在是[1, 2, 3, 4, 5, 6]

# 用 "in" 测试列表是否包含值
1 in li   # =&gt; True

# 用 "len()" 取列表长度
len(li)   # =&gt; 6


# 元组类似列表，但是不允许修改
tup = (1, 2, 3)
tup[0]   # =&gt; 1
tup[0] = 3  # 抛出 TypeError

# 如果元素数量为 1 的元组必须在元素之后加一个逗号
# 其他元素数量的元组，包括空元组，都不需要
type((1))   # =&gt; &lt;class 'int'&gt;
type((1,))  # =&gt; &lt;class 'tuple'&gt;
type(())    # =&gt; &lt;class 'tuple'&gt;

# 列表允许的操作元组大多都可以
len(tup)   # =&gt; 3
tup + (4, 5, 6)   # =&gt; (1, 2, 3, 4, 5, 6)
tup[:2]   # =&gt; (1, 2)
2 in tup   # =&gt; True

# 可以把元组合列表解包，赋值给变量
a, b, c = (1, 2, 3)     # 现在 a 是 1，b 是 2，c 是 3
# 也可以做扩展解包
a, *b, c = (1, 2, 3, 4)  # 现在 a 是 1, b 是 [2, 3]， c 是 4
# 元组周围的括号是可以省略的
d, e, f = 4, 5, 6 # 元组 4, 5, 6 通过解包被赋值给变量 d, e, f
# 交换两个变量的值就这么简单
e, d = d, e     # 现在 d 是 5，e 是 4


# 字典用来存储 key 到 value 的映射关系
empty_dict = {}
# 初始化的字典
filled_dict = {"one": 1, "two": 2, "three": 3}

# 字典的 key 必须为不可变类型。 这是为了确保 key 被转换为唯一的哈希值以用于快速查询
# 不可变类型包括整数、浮点、字符串、元组
invalid_dict = {[1,2,3]: "123"}  # =&gt; 抛出 TypeError: unhashable type: 'list'
valid_dict = {(1,2,3):[1,2,3]}   # 然而 value 可以是任何类型

# 用[]取值
filled_dict["one"]   # =&gt; 1

# 用 keys 获得所有的键。
# 因为 keys 返回一个可迭代对象，所以我们需要把它包在 "list()" 里才能转换为列表。
# 我们下面会详细介绍可迭代。
# 注意: 对于版本 &lt; 3.7 的 python, 字典的 key 的排序是无序的。你的运行结果
# 可能与下面的例子不符，但是在 3.7 版本，字典中的项会按照他们被插入到字典的顺序进行排序
list(filled_dict.keys())  # =&gt; ["three", "two", "one"] Python 版本 &lt;3.7
list(filled_dict.keys())  # =&gt; ["one", "two", "three"] Python 版本 3.7+

# 用 "values()" 获得所有的值。跟 keys 一样也是可迭代对象，要使用 "list()" 才能转换为列表。
# 注意: 排序顺序和 keys 的情况相同。

list(filled_dict.values())  # =&gt; [3, 2, 1] Python 版本 &lt; 3.7
list(filled_dict.values())  # =&gt; [1, 2, 3] Python 版本 3.7+


# 用in测试一个字典是否包含一个键
"one" in filled_dict   # =&gt; True
1 in filled_dict   # =&gt; False

# 访问不存在的键会导致 KeyError
filled_dict["four"]   # KeyError

# 用 "get()" 来避免KeyError
filled_dict.get("one")      # =&gt; 1
filled_dict.get("four")     # =&gt; None
# 当键不存在的时候 "get()" 方法可以返回默认值
filled_dict.get("one", 4)   # =&gt; 1
filled_dict.get("four", 4)  # =&gt; 4

# "setdefault()" 方法只有当键不存在的时候插入新值
filled_dict.setdefault("five", 5)  # filled_dict["five"] 设为5
filled_dict.setdefault("five", 6)  # filled_dict["five"] 还是5

# 字典赋值
filled_dict.update({"four":4}) # =&gt; {"one": 1, "two": 2, "three": 3, "four": 4}
filled_dict["four"] = 4        # 另一种赋值方法

# 用 del 删除项
del filled_dict["one"]  # 从 filled_dict 中把 one 删除


# 用 set 表达集合
empty_set = set()
# 初始化一个集合，语法跟字典相似。
some_set = {1, 1, 2, 2, 3, 4}   # some_set现在是 {1, 2, 3, 4}

# 类似字典的 keys，set 的元素也必须是不可变类型
invalid_set = {[1], 1}  # =&gt; Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}

# 可以把集合赋值于变量
filled_set = some_set

# 为集合添加元素
filled_set.add(5)   # filled_set 现在是 {1, 2, 3, 4, 5}
# set 没有重复的元素
filled_set.add(5)   # filled_set 依然是 {1, 2, 3, 4, 5}

# "&amp;" 取交集
other_set = {3, 4, 5, 6}
filled_set &amp; other_set   # =&gt; {3, 4, 5}

# "|" 取并集
filled_set | other_set   # =&gt; {1, 2, 3, 4, 5, 6}

# "-" 取补集
{1, 2, 3, 4} - {2, 3, 5}   # =&gt; {1, 4}

# "^" 取异或集（对称差）
{1, 2, 3, 4} ^ {2, 3, 5}  # =&gt; {1, 4, 5}

# 判断左边的集合是否是右边集合的超集
{1, 2} &gt;= {1, 2, 3} # =&gt; False

# 判断左边的集合是否是右边集合的子集
{1, 2} &lt;= {1, 2, 3} # =&gt; True

# in 测试集合是否包含元素
2 in filled_set   # =&gt; True
10 in filled_set   # =&gt; False

# 单层集合的深度复制
filled_set = some_set.copy()  # filled_set 是 {1, 2, 3, 4, 5}
filled_set is some_set        # =&gt; False
</code></pre>
<h1 id="heading-5rwb56il5o6n5yi25zkm6lt5luj5zmo">流程控制和迭代器</h1>
<pre><code class="lang-plaintext"># 先随便定义一个变量
some_var = 5

# 这是个if语句。注意缩进在Python里是有意义的！
# 缩进要使用 4 个空格而不是 tabs。
# 这段代码会打印 "some_var is smaller than 10"
if some_var &gt; 10:
    print("some_var is totally bigger than 10.")
elif some_var &lt; 10:    # elif 语句是可选的
    print("some_var is smaller than 10.")
else:                  # else 也是可选的
    print("some_var is indeed 10.")


"""
用 for 循环语句遍历列表
打印:
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    # 你可以使用 format() 格式化字符串并插入值
    print("{} is a mammal".format(animal))

"""
"range(number)" 返回数字列表从 0 到 number 的数字
打印:
    0
    1
    2
    3
"""
for i in range(4):
    print(i)

"""
"range(lower, upper)" 会返回一个包含从 lower 到 upper 的数字迭代器
prints:
    4
    5
    6
    7
"""
for i in range(4, 8):
    print(i)

"""
"range(lower, upper, step)" 会返回一个，从 lower 到 upper、并且间隔值为 step 的迭代器。
如果 step 未传入则会使用默认值 1
prints:
    4
    6
"""
for i in range(4, 8, 2):
    print(i)

"""
遍历列表，并且同时返回列表里的每一个元素的索引和数值。
prints:
    0 dog
    1 cat
    2 mouse
"""
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
    print(i, value)

"""
while 循环直到条件不满足
打印:
    0
    1
    2
    3
"""
x = 0
while x &lt; 4:
    print(x)
    x += 1  # x = x + 1 的简写


# 用 try/except 块处理异常状况
try:
    # 用 raise 抛出异常
    raise IndexError("This is an index error")
except IndexError as e:
    pass                             # pass 是无操作，但是应该在这里处理错误
except (TypeError, NameError):
    pass                             # 可以同时处理不同类的错误
else:                    # else语句是可选的，必须在所有的except之后
    print("All good!")   # 只有当try运行完没有错误的时候这句才会运行
finally:                                 # 在任何情况下都会执行
         print("We can clean up resources here")

# 你可以使用 with 语句来代替 try/finally 对操作进行结束的操作
with open("myfile.txt") as f:
    for line in f:
        print(line)

# 写入文件
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
    file.write(str(contents))        # 写入字符串到文件

with open("myfile2.txt", "w+") as file:
    file.write(json.dumps(contents)) # 写入对象到文件

# Reading from a file
with open("myfile1.txt", "r+") as file:
    contents = file.read()           # 从文件读取字符串
print(contents)
# print: {"aa": 12, "bb": 21}

with open("myfile2.txt", "r+") as file:
    contents = json.load(file)       # 从文件读取 json 对象
print(contents)
# print: {"aa": 12, "bb": 21}

# Windows 环境调用 open() 读取文件的默认编码为 ANSI，如果需要读取 utf-8 编码的文件，
# 需要指定 encoding 参数:
# open("myfile3.txt", "r+", encoding = "utf-8")


# Python 提供一个叫做可迭代 (iterable) 的基本抽象。一个可迭代对象是可以被当作序列
# 的对象。比如说上面 range 返回的对象就是可迭代的。

filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable) # =&gt; dict_keys(['one', 'two', 'three'])，是一个实现可迭代接口的对象

# 可迭代对象可以遍历
for i in our_iterable:
    print(i)    # 打印 one, two, three

# 但是不可以随机访问
our_iterable[1]  # 抛出TypeError

# 可迭代对象知道怎么生成迭代器
our_iterator = iter(our_iterable)

# 迭代器是一个可以记住遍历的位置的对象
# 用 "next()" 获得下一个对象
next(our_iterator)  # =&gt; "one"

# 再一次调取 "next()" 时会记得位置
next(our_iterator)  # =&gt; "two"
next(our_iterator)  # =&gt; "three"

# 当迭代器所有元素都取出后，会抛出 StopIteration
next(our_iterator) # 抛出 StopIteration

# 我们还可以通过遍历访问所有的值，实际上，for 内部实现了迭代
our_iterator = iter(our_iterable)
for i in our_iterator:
    print(i)  # 依次打印 one, two, three

# 可以用 list 一次取出迭代器或者可迭代对象所有的元素
list(filled_dict.keys())  # =&gt; 返回 ["one", "two", "three"]
list(our_iterator)  # =&gt; 返回 [] 因为迭代的位置被保存了
</code></pre>
<h1 id="heading-5ye95pww">函数</h1>
<pre><code class="lang-plaintext"># 用def定义新函数
def add(x, y):
    print("x is {} and y is {}".format(x, y))
    return x + y    # 用 return 语句返回

# 调用函数
add(5, 6)   # =&gt; 打印 "x is 5 and y is 6" 并且返回 11

# 也可以用关键字参数来调用函数
add(y=6, x=5)   # 关键字参数可以用任何顺序


# 我们可以定义一个可变参数函数
def varargs(*args):
    return args

varargs(1, 2, 3)   # =&gt; (1, 2, 3)


# 我们也可以定义一个关键字可变参数函数
def keyword_args(**kwargs):
    return kwargs

# 我们来看看结果是什么：
keyword_args(big="foot", loch="ness")   # =&gt; {"big": "foot", "loch": "ness"}


# 这两种可变参数可以混着用
def all_the_args(*args, **kwargs):
    print(args)
    print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) prints:
    (1, 2)
    {"a": 3, "b": 4}
"""

# 调用可变参数函数时可以做跟上面相反的，用 * 展开元组，用 ** 展开字典。
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args)   # 相当于 all_the_args(1, 2, 3, 4)
all_the_args(**kwargs)   # 相当于 all_the_args(a=3, b=4)
all_the_args(*args, **kwargs)   # 相当于 all_the_args(1, 2, 3, 4, a=3, b=4)

# 使用返回多个数值（返回值为元组类型）
def swap(x, y):
    return y, x  # 用不带括号的元组的格式来返回多个数值
                 # (注意: 括号不需要加，但是也可以加)

x = 1
y = 2
x, y = swap(x, y)     # =&gt; x = 2, y = 1
# (x, y) = swap(x,y)  # 同上，括号不需要加，但是也可以加


# 函数作用域
x = 5

def setX(num):
    # 局部作用域的 x 和全局域的 x 是不同的
    x = num # =&gt; 43
    print (x) # =&gt; 43

def setGlobalX(num):
    global x
    print (x) # =&gt; 5
    x = num   # 现在全局域的 x 被赋值
    print (x) # =&gt; 6

setX(43)
setGlobalX(6)


# 函数在 Python 是一等公民
def create_adder(x):
    def adder(y):
        return x + y
    return adder

add_10 = create_adder(10)
add_10(3)   # =&gt; 13

# 也有匿名函数
(lambda x: x &gt; 2)(3)                  # =&gt; True
(lambda x, y: x ** 2 + y ** 2)(2, 1)  # =&gt; 5

# 内置的高阶函数
list(map(add_10, [1, 2, 3]))          # =&gt; [11, 12, 13]
list(map(max, [1, 2, 3], [4, 2, 1]))  # =&gt; [4, 2, 3]

list(filter(lambda x: x &gt; 5, [3, 4, 5, 6, 7]))  # =&gt; [6, 7]

# 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。
[add_10(i) for i in [1, 2, 3]]  # =&gt; [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x &gt; 5]   # =&gt; [6, 7]

# 你也可以用这种方式实现对集合和字典的构建
{x for x in 'abcddeef' if x not in 'abc'}  # =&gt; {'d', 'e', 'f'}
{x: x**2 for x in range(5)}  # =&gt; {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
</code></pre>
<h1 id="heading-5qih5z2x">模块</h1>
<pre><code class="lang-plaintext"># 导入模块
import math
print(math.sqrt(16))  # =&gt; 4.0

# 你可以导入模块中具体的函数
from math import ceil, floor
print(ceil(3.7))   # =&gt; 4.0
print(floor(3.7))  # =&gt; 3.0

# 你可以导入模块中的所有的函数
# 警告: 此操作不推荐
from math import *

# 你可以对模块名进行简化
import math as m
math.sqrt(16) == m.sqrt(16)  # =&gt; True

# Python 模块实质上是 Python 文件
# 你可以自己编写自己的模块，然后导入
# 模块的名称和文件名相同

# 你可以用 "dir()" 查看模块中定义的函数和字段
import math
dir(math)

# 当你的脚本文件所在的文件夹也包含了一个名为 math.py 的 Python 文件
# 这个 math.py 文件会被代替引入，而不是引入 Python 內建模块中的 math
# 出现这个情况的原因是本地文件夹的引入优先级要比 Python 內建库引入优先级要高
</code></pre>
<h1 id="heading-57g7">类</h1>
<pre><code class="lang-plaintext"># 我们使用 "class" 语句来创建类
class Human:

    # 一个类的字段。 这个字段共享给这个类的所有实例。
    species = "H. sapiens"

    # 构造方法，当实例被初始化时被调用。注意名字前后的双下划线，这是表明这个属性
    # 或方法对 Python 有特殊意义，但是允许用户自行定义。
    # 方法(可能是对象或者属性) 类似: __init__, __str__,__repr__ etc
    # 都是特殊的方法
    # 你自己取名时不应该用这种格式
    def __init__(self, name):
        # 将参数赋值给实例的 name 字段
        self.name = name

        # 初始化属性
        self._age = 0

    # 实例方法，第一个参数总是self，也就是这个实例对象
    def say(self, msg):
        print("{name}: {message}".format(name=self.name, message=msg))

    # 另一个实例方法
    def sing(self):
        return 'yo... yo... microphone check... one two... one two...'

    # 类方法，被所有此类的实例共用。
    # 第一个参数是这个类对象。
    @classmethod
    def get_species(cls):
        return cls.species

    # 静态方法。调用时没有实例或类的绑定。
    @staticmethod
    def grunt():
        return "*grunt*"

    # property 有点类似 getter
    # 它把方法 age() 转换为同名并且只读的属性
    # 通常情况下，可以不需要编写复杂的 getter 和 setter。
    @property
    def age(self):
        return self._age

    # 允许属性被修改
    @age.setter
    def age(self, age):
        self._age = age

    # 允许属性被删除
    @age.deleter
    def age(self):
        del self._age

# 当 Python 解释器在读取源文件的时候，就会执行文件中所有的代码
# 对 __name__ 的检查可以保证这块代码只会在这个模块是主程序的情况下被运行（而不是在引用时运行）
if __name__ == '__main__':
    # 
    i = Human(name="Ian")
    i.say("hi")                     # "Ian: hi"
    j = Human("Joel")
    j.say("hello")                  # "Joel: hello"
    # i 和 j 都是 Human 实例化后的对象，换一句话说，它们都是 Human 实例

    # 运行类方法 (classmethod)
    i.say(i.get_species())          # "Ian: H. sapiens"
    # 修改共享的类属性
    Human.species = "H. neanderthalensis"
    i.say(i.get_species())          # =&gt; "Ian: H. neanderthalensis"
    j.say(j.get_species())          # =&gt; "Joel: H. neanderthalensis"

    # 运行静态方法 (staticmethod)
    print(Human.grunt())            # =&gt; "*grunt*"

    # 实例上也可以执行静态方法
    print(i.grunt())                # =&gt; "*grunt*"

    # 更新实例的属性
    i.age = 42
    # 访问实例的属性
    i.say(i.age)                    # =&gt; "Ian: 42"
    j.say(j.age)                    # =&gt; "Joel: 0"
    # 删除实例的属性
    del i.age
    # i.age                         # =&gt; 这会抛出一个错误: AttributeError


####################################################
## 6.1 类的继承
####################################################

# 继承机制允许子类可以继承父类上的方法和变量。
# 我们可以把 Human 类作为一个基础类或者说叫做父类，
# 然后定义一个名为 Superhero 的子类来继承父类上的比如 "species"、 "name"、 "age" 的属性
# 和比如 "sing" 、"grunt" 这样的方法，同时，也可以定义它自己独有的属性

# 基于 Python 文件模块化的特点，你可以把这个类放在独立的文件中，比如说，human.py。

# 要从别的文件导入函数，需要使用以下的语句
# from "filename-without-extension" import "function-or-class"

from human import Human

# 指定父类作为类初始化的参数
class Superhero(Human):

    # 如果子类需要继承所有父类的定义，并且不需要做任何的修改，
    # 你可以直接使用 "pass" 关键字（并且不需要其他任何语句）
    # 但是在这个例子中会被注释掉，以用来生成不一样的子类。
    # pass

    # 子类可以重写父类定义的字段
    species = 'Superhuman'

    # 子类会自动的继承父类的构造函数包括它的参数，但同时，子类也可以新增额外的参数或者定义，
    # 甚至去覆盖父类的方法比如说构造函数。
    # 这个构造函数从父类 "Human" 上继承了 "name" 参数，同时又新增了 "superpower" 和
    # "movie" 参数:
    def __init__(self, name, movie=False,
                 superpowers=["super strength", "bulletproofing"]):

        # 新增额外类的参数
        self.fictional = True
        self.movie = movie
        # 注意可变的默认值，因为默认值是共享的
        self.superpowers = superpowers

        # "super" 函数让你可以访问父类中被子类重写的方法
        # 在这个例子中，被重写的是 __init__ 方法
        # 这个语句是用来运行父类的构造函数:
        super().__init__(name)

    # 重写父类中的 sing 方法
    def sing(self):
        return 'Dun, dun, DUN!'

    # 新增一个额外的方法
    def boast(self):
        for power in self.superpowers:
            print("I wield the power of {pow}!".format(pow=power))


if __name__ == '__main__':
    sup = Superhero(name="Tick")

    # 检查实例类型
    if isinstance(sup, Human):
        print('I am human')
    if type(sup) is Superhero:
        print('I am a superhero')

    # 获取方法解析顺序 MRO，MRO 被用于 getattr() 和 super()
    # 这个字段是动态的，并且可以被修改
    print(Superhero.__mro__)    # =&gt; (&lt;class '__main__.Superhero'&gt;,
                                # =&gt; &lt;class 'human.Human'&gt;, &lt;class 'object'&gt;)

    # 调用父类的方法并且使用子类的属性
    print(sup.get_species())    # =&gt; Superhuman

    # 调用被重写的方法
    print(sup.sing())           # =&gt; Dun, dun, DUN!

    # 调用 Human 的方法
    sup.say('Spoon')            # =&gt; Tick: Spoon

    # 调用 Superhero 独有的方法
    sup.boast()                 # =&gt; I wield the power of super strength!
                                # =&gt; I wield the power of bulletproofing!

    # 继承类的字段
    sup.age = 31
    print(sup.age)              # =&gt; 31

    # Superhero 独有的字段
    print('Am I Oscar eligible? ' + str(sup.movie))


####################################################
## 6.2 多重继承
####################################################

# 定义另一个类
# bat.py
class Bat:

    species = 'Baty'

    def __init__(self, can_fly=True):
        self.fly = can_fly

    # 这个类同样有 say 的方法
    def say(self, msg):
        msg = '... ... ...'
        return msg

    # 新增一个独有的方法
    def sonar(self):
        return '))) ... ((('

if __name__ == '__main__':
    b = Bat()
    print(b.say('hello'))
    print(b.fly)

# 现在我们来定义一个类来同时继承 Superhero 和 Bat
# superhero.py
from superhero import Superhero
from bat import Bat

# 定义 Batman 作为子类，来同时继承 SuperHero 和 Bat
class Batman(Superhero, Bat):

    def __init__(self, *args, **kwargs):
        # 通常要继承属性，你必须调用 super:
        # super(Batman, self).__init__(*args, **kwargs)
        # 然而在这里我们处理的是多重继承，而 super() 只会返回 MRO 列表的下一个基础类。
        # 因此，我们需要显式调用初始类的 __init__
        # *args 和 **kwargs 传递参数时更加清晰整洁，而对于父类而言像是 “剥了一层洋葱”
        Superhero.__init__(self, 'anonymous', movie=True,
                           superpowers=['Wealthy'], *args, **kwargs)
        Bat.__init__(self, *args, can_fly=False, **kwargs)
        # 重写了 name 字段
        self.name = 'Sad Affleck'

    def sing(self):
        return 'nan nan nan nan nan batman!'


if __name__ == '__main__':
    sup = Batman()

    # 获取方法解析顺序 MRO，MRO 被用于 getattr() 和 super()
    # 这个字段是动态的，并且可以被修改
    print(Batman.__mro__)       # =&gt; (&lt;class '__main__.Batman'&gt;,
                                # =&gt; &lt;class 'superhero.Superhero'&gt;,
                                # =&gt; &lt;class 'human.Human'&gt;,
                                # =&gt; &lt;class 'bat.Bat'&gt;, &lt;class 'object'&gt;)

    # 调用父类的方法并且使用子类的属性
    print(sup.get_species())    # =&gt; Superhuman

    # 调用被重写的类
    print(sup.sing())           # =&gt; nan nan nan nan nan batman!

    # 调用 Human 上的方法，(之所以是 Human 而不是 Bat)，是因为继承顺序起了作用
    sup.say('I agree')          # =&gt; Sad Affleck: I agree

    # 调用仅存在于第二个继承的父类的方法
    print(sup.sonar())          # =&gt; ))) ... (((

    # 继承类的属性
    sup.age = 100
    print(sup.age)              # =&gt; 100

    # 从第二个类上继承字段，并且其默认值被重写
    print('Can I fly? ' + str(sup.fly)) # =&gt; Can I fly? False
</code></pre>
<h1 id="heading-6auy57qn55so5rov">高级用法</h1>
<pre><code class="lang-plaintext"># 用生成器(generators)方便地写惰性运算
def double_numbers(iterable):
    for i in iterable:
        yield i + i

# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值，而不是把所有的
# 值全部算好。
#
# range的返回值也是一个生成器，不然一个1到900000000的列表会花很多时间和内存。
#
# 如果你想用一个Python的关键字当作变量名，可以加一个下划线来区分。
range_ = range(1, 900000000)
# 当找到一个 &gt;=30 的结果就会停
# 这意味着 `double_numbers` 不会生成大于30的数。
for i in double_numbers(range_):
    print(i)
    if i &gt;= 30:
        break
# 你也可以把一个生成器推导直接转换为列表
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
print(gen_to_list)  # =&gt; [-1, -2, -3, -4, -5]


# 装饰器(decorators)
# 这个例子中，beg装饰say
# beg会先调用say。如果返回的say_please为真，beg会改变返回的字符串。
from functools import wraps


def beg(target_function):
    @wraps(target_function)
    def wrapper(*args, **kwargs):
        msg, say_please = target_function(*args, **kwargs)
        if say_please:
            return "{} {}".format(msg, "Please! I am poor :(")
        return msg

    return wrapper


@beg
def say(say_please=False):
    msg = "Can you buy me a beer?"
    return msg, say_please


print(say())  # Can you buy me a beer?
print(say(say_please=True))  # Can you buy me a beer? Please! I am poor :(
</code></pre>
]]></content:encoded></item><item><title><![CDATA[关于aq语言语法设计有关事项的公告]]></title><description><![CDATA[由于目前的开发工作遇到较多的问题，同时底层代码混乱，存在较多的安全隐患的缺陷，同时语法仍未存在稳定的标准和统一的规定。即日起，对于有关AQ的项目暂缓开发，直到形成主要的语言语法指南后恢复开发工作。
相关更新见AQ Developer Blog和Github。
如有疑问，请联系我们。
更多有关报告详见后续发布。]]></description><link>https://blog.axa6.com/aq-1-1</link><guid isPermaLink="true">https://blog.axa6.com/aq-1-1</guid><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Thu, 20 Mar 2025 12:28:22 GMT</pubDate><content:encoded><![CDATA[<p>由于目前的开发工作遇到较多的问题，同时底层代码混乱，存在较多的安全隐患的缺陷，同时语法仍未存在稳定的标准和统一的规定。即日起，对于有关AQ的项目暂缓开发，直到形成主要的语言语法指南后恢复开发工作。</p>
<p>相关更新见<a target="_blank" href="https://blog.axa6.com/">AQ Developer Blog</a>和<a target="_blank" href="https://github.com/aq-org/AQ">Github</a>。</p>
<p>如有疑问，请<a target="_blank" href="mailto:xie.zicong@axa6.com">联系我们</a>。</p>
<p>更多有关报告详见后续发布。</p>
]]></content:encoded></item><item><title><![CDATA[List of referenced programming language syntax designs]]></title><description><![CDATA[From Learn X in Y Minutes: Scenic Programming Language Tours
Bash:
#!/usr/bin/env bash
# First line of the script is the shebang which tells the system how to execute
# the script: https://en.wikipedia.org/wiki/Shebang_(Unix)
# As you already figured...]]></description><link>https://blog.axa6.com/list-of-referenced-programming-language-syntax-designs</link><guid isPermaLink="true">https://blog.axa6.com/list-of-referenced-programming-language-syntax-designs</guid><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Thu, 20 Mar 2025 12:21:08 GMT</pubDate><content:encoded><![CDATA[<p>From <a target="_blank" href="https://learnxinyminutes.com/">Learn X in Y Minutes: Scenic Programming Language Tours</a></p>
<p>Bash:</p>
<pre><code class="lang-plaintext">#!/usr/bin/env bash
# First line of the script is the shebang which tells the system how to execute
# the script: https://en.wikipedia.org/wiki/Shebang_(Unix)
# As you already figured, comments start with #. Shebang is also a comment.

# Simple hello world example:
echo "Hello world!" # =&gt; Hello world!

# Each command starts on a new line, or after a semicolon:
echo "This is the first command"; echo "This is the second command"
# =&gt; This is the first command
# =&gt; This is the second command

# Declaring a variable looks like this:
variable="Some string"

# But not like this:
variable = "Some string" # =&gt; returns error "variable: command not found"
# Bash will decide that `variable` is a command it must execute and give an error
# because it can't be found.

# Nor like this:
variable= "Some string" # =&gt; returns error: "Some string: command not found"
# Bash will decide that "Some string" is a command it must execute and give an
# error because it can't be found. In this case the "variable=" part is seen
# as a variable assignment valid only for the scope of the "Some string"
# command.

# Using the variable:
echo "$variable" # =&gt; Some string
echo '$variable' # =&gt; $variable
# When you use a variable itself — assign it, export it, or else — you write
# its name without $. If you want to use the variable's value, you should use $.
# Note that ' (single quote) won't expand variables!
# You can write variables without surrounding double quotes but it's not
# recommended due to how Bash handles variables with spaces in them.

# Parameter expansion ${...}:
echo "${variable}" # =&gt; Some string
# This is a simple usage of parameter expansion such as two examples above.
# Parameter expansion gets a value from a variable.
# It "expands" or prints the value.
# During the expansion time the value or parameter can be modified.
# Below are other modifications that add onto this expansion.

# String substitution in variables:
echo "${variable/Some/A}" # =&gt; A string
# This will substitute the first occurrence of "Some" with "A".

# Substring from a variable:
length=7
echo "${variable:0:length}" # =&gt; Some st
# This will return only the first 7 characters of the value
echo "${variable: -5}" # =&gt; tring
# This will return the last 5 characters (note the space before -5).
# The space before minus is mandatory here.

# String length:
echo "${#variable}" # =&gt; 11

# Indirect expansion:
other_variable="variable"
echo ${!other_variable} # =&gt; Some string
# This will expand the value of `other_variable`.

# The default value for variable:
echo "${foo:-"DefaultValueIfFooIsMissingOrEmpty"}"
# =&gt; DefaultValueIfFooIsMissingOrEmpty
# This works for null (foo=) and empty string (foo=""); zero (foo=0) returns 0.
# Note that it only returns default value and doesn't change variable value.

# Declare an array with 6 elements:
array=(one two three four five six)
# Print the first element:
echo "${array[0]}" # =&gt; "one"
# Print all elements:
echo "${array[@]}" # =&gt; "one two three four five six"
# Print the number of elements:
echo "${#array[@]}" # =&gt; "6"
# Print the number of characters in third element
echo "${#array[2]}" # =&gt; "5"
# Print 2 elements starting from fourth:
echo "${array[@]:3:2}" # =&gt; "four five"
# Print all elements each of them on new line.
for item in "${array[@]}"; do
    echo "$item"
done

# Built-in variables:
# There are some useful built-in variables, like:
echo "Last program's return value: $?"
echo "Script's PID: $$"
echo "Number of arguments passed to script: $#"
echo "All arguments passed to script: $@"
echo "Script's arguments separated into different variables: $1 $2..."

# Brace Expansion {...}
# used to generate arbitrary strings:
echo {1..10} # =&gt; 1 2 3 4 5 6 7 8 9 10
echo {a..z} # =&gt; a b c d e f g h i j k l m n o p q r s t u v w x y z
# This will output the range from the start value to the end value.
# Note that you can't use variables here:
from=1
to=10
echo {$from..$to} # =&gt; {$from..$to}

# Now that we know how to echo and use variables,
# let's learn some of the other basics of Bash!

# Our current directory is available through the command `pwd`.
# `pwd` stands for "print working directory".
# We can also use the built-in variable `$PWD`.
# Observe that the following are equivalent:
echo "I'm in $(pwd)" # execs `pwd` and interpolates output
echo "I'm in $PWD" # interpolates the variable

# If you get too much output in your terminal, or from a script, the command
# `clear` clears your screen:
clear
# Ctrl-L also works for clearing output.

# Reading a value from input:
echo "What's your name?"
read name
# Note that we didn't need to declare a new variable.
echo "Hello, $name!"

# We have the usual if structure.
# Condition is true if the value of $name is not equal to the current user's login username:
if [[ "$name" != "$USER" ]]; then
    echo "Your name isn't your username"
else
    echo "Your name is your username"
fi

# To use &amp;&amp; and || with if statements, you need multiple pairs of square brackets:
read age
if [[ "$name" == "Steve" ]] &amp;&amp; [[ "$age" -eq 15 ]]; then
    echo "This will run if $name is Steve AND $age is 15."
fi

if [[ "$name" == "Daniya" ]] || [[ "$name" == "Zach" ]]; then
    echo "This will run if $name is Daniya OR Zach."
fi
# There are other comparison operators for numbers listed below:
# -ne - not equal
# -lt - less than
# -gt - greater than
# -le - less than or equal to
# -ge - greater than or equal to

# There is also the `=~` operator, which tests a string against the Regex pattern:
email=me@example.com
if [[ "$email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]]
then
    echo "Valid email!"
fi

# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
# =&gt; Always executed
echo "Always executed" &amp;&amp; echo "Only executed if first command does NOT fail"
# =&gt; Always executed
# =&gt; Only executed if first command does NOT fail

# A single ampersand &amp; after a command runs it in the background. A background command's
# output is printed to the terminal, but it cannot read from the input.
sleep 30 &amp;
# List background jobs
jobs # =&gt; [1]+  Running                 sleep 30 &amp;
# Bring the background job to the foreground
fg
# Ctrl-C to kill the process, or Ctrl-Z to pause it
# Resume a background process after it has been paused with Ctrl-Z
bg
# Kill job number 2
kill %2
# %1, %2, etc. can be used for fg and bg as well

# Redefine command `ping` as alias to send only 5 packets
alias ping='ping -c 5'
# Escape the alias and use command with this name instead
\ping 192.168.1.1
# Print all aliases
alias -p

# Expressions are denoted with the following format:
echo $(( 10 + 5 )) # =&gt; 15

# Unlike other programming languages, bash is a shell so it works in the context
# of a current directory. You can list files and directories in the current
# directory with the ls command:
ls # Lists the files and subdirectories contained in the current directory

# This command has options that control its execution:
ls -l # Lists every file and directory on a separate line
ls -t # Sorts the directory contents by last-modified date (descending)
ls -R # Recursively `ls` this directory and all of its subdirectories

# Results (stdout) of the previous command can be passed as input (stdin) to the next command
# using a pipe |. Commands chained in this way are called a "pipeline", and are run concurrently.
# The `grep` command filters the input with provided patterns.
# That's how we can list .txt files in the current directory:
ls -l | grep "\.txt"

# Use `cat` to print files to stdout:
cat file.txt

# We can also read the file using `cat`:
Contents=$(cat file.txt)
# "\n" prints a new line character
# "-e" to interpret the newline escape characters as escape characters
echo -e "START OF FILE\n$Contents\nEND OF FILE"
# =&gt; START OF FILE
# =&gt; [contents of file.txt]
# =&gt; END OF FILE

# Use `cp` to copy files or directories from one place to another.
# `cp` creates NEW versions of the sources,
# so editing the copy won't affect the original (and vice versa).
# Note that it will overwrite the destination if it already exists.
cp srcFile.txt clone.txt
cp -r srcDirectory/ dst/ # recursively copy

# Look into `scp` or `sftp` if you plan on exchanging files between computers.
# `scp` behaves very similarly to `cp`.
# `sftp` is more interactive.

# Use `mv` to move files or directories from one place to another.
# `mv` is similar to `cp`, but it deletes the source.
# `mv` is also useful for renaming files!
mv s0urc3.txt dst.txt # sorry, l33t hackers...

# Since bash works in the context of a current directory, you might want to
# run your command in some other directory. We have cd for changing location:
cd ~    # change to home directory
cd      # also goes to home directory
cd ..   # go up one directory
        # (^^say, from /home/username/Downloads to /home/username)
cd /home/username/Documents   # change to specified directory
cd ~/Documents/..    # now in home directory (if ~/Documents exists)
cd -    # change to last directory
# =&gt; /home/username/Documents

# Use subshells to work across directories
(echo "First, I'm here: $PWD") &amp;&amp; (cd someDir; echo "Then, I'm here: $PWD")
pwd # still in first directory

# Use `mkdir` to create new directories.
mkdir myNewDir
# The `-p` flag causes new intermediate directories to be created as necessary.
mkdir -p myNewDir/with/intermediate/directories
# if the intermediate directories didn't already exist, running the above
# command without the `-p` flag would return an error

# You can redirect command input and output (stdin, stdout, and stderr)
# using "redirection operators". Unlike a pipe, which passes output to a command,
# a redirection operator has a command's input come from a file or stream, or
# sends its output to a file or stream.

# Read from stdin until ^EOF$ and overwrite hello.py with the lines
# between "EOF" (which are called a "here document"):
cat &gt; hello.py &lt;&lt; EOF
#!/usr/bin/env python
from __future__ import print_function
import sys
print("#stdout", file=sys.stdout)
print("#stderr", file=sys.stderr)
for line in sys.stdin:
    print(line, file=sys.stdout)
EOF
# Variables will be expanded if the first "EOF" is not quoted

# Run the hello.py Python script with various stdin, stdout, and
# stderr redirections:
python hello.py &lt; "input.in" # pass input.in as input to the script

python hello.py &gt; "output.out" # redirect output from the script to output.out

python hello.py 2&gt; "error.err" # redirect error output to error.err

python hello.py &gt; "output-and-error.log" 2&gt;&amp;1
# redirect both output and errors to output-and-error.log
# &amp;1 means file descriptor 1 (stdout), so 2&gt;&amp;1 redirects stderr (2) to the current
# destination of stdout (1), which has been redirected to output-and-error.log.

python hello.py &gt; /dev/null 2&gt;&amp;1
# redirect all output and errors to the black hole, /dev/null, i.e., no output

# The output error will overwrite the file if it exists,
# if you want to append instead, use "&gt;&gt;":
python hello.py &gt;&gt; "output.out" 2&gt;&gt; "error.err"

# Overwrite output.out, append to error.err, and count lines:
info bash 'Basic Shell Features' 'Redirections' &gt; output.out 2&gt;&gt; error.err
wc -l output.out error.err

# Run a command and print its file descriptor (e.g. /dev/fd/123)
# see: man fd
echo &lt;(echo "#helloworld")

# Overwrite output.out with "#helloworld":
cat &gt; output.out &lt;(echo "#helloworld")
echo "#helloworld" &gt; output.out
echo "#helloworld" | cat &gt; output.out
echo "#helloworld" | tee output.out &gt;/dev/null

# Cleanup temporary files verbosely (add '-i' for interactive)
# WARNING: `rm` commands cannot be undone
rm -v output.out error.err output-and-error.log
rm -r tempDir/ # recursively delete
# You can install the `trash-cli` Python package to have `trash`
# which puts files in the system trash and doesn't delete them directly
# see https://pypi.org/project/trash-cli/ if you want to be careful

# Commands can be substituted within other commands using $( ):
# The following command displays the number of files and directories in the
# current directory.
echo "There are $(ls | wc -l) items here."

# The same can be done using backticks `` but they can't be nested -
# the preferred way is to use $( ).
echo "There are `ls | wc -l` items here."

# Bash uses a `case` statement that works similarly to switch in Java and C++:
case "$Variable" in
    # List patterns for the conditions you want to meet
    0) echo "There is a zero.";;
    1) echo "There is a one.";;
    *) echo "It is not null.";;  # match everything
esac

# `for` loops iterate for as many arguments given:
# The contents of $Variable is printed three times.
for Variable in {1..3}
do
    echo "$Variable"
done
# =&gt; 1
# =&gt; 2
# =&gt; 3


# Or write it the "traditional for loop" way:
for ((a=1; a &lt;= 3; a++))
do
    echo $a
done
# =&gt; 1
# =&gt; 2
# =&gt; 3

# They can also be used to act on files..
# This will run the command `cat` on file1 and file2
for Variable in file1 file2
do
    cat "$Variable"
done

# ..or the output from a command
# This will `cat` the output from `ls`.
for Output in $(ls)
do
    cat "$Output"
done

# Bash can also accept patterns, like this to `cat`
# all the Markdown files in current directory
for Output in ./*.markdown
do
    cat "$Output"
done

# while loop:
while [ true ]
do
    echo "loop body here..."
    break
done
# =&gt; loop body here...

# You can also define functions
# Definition:
function foo ()
{
    echo "Arguments work just like script arguments: $@"
    echo "And: $1 $2..."
    echo "This is a function"
    returnValue=0    # Variable values can be returned
    return $returnValue
}
# Call the function `foo` with two arguments, arg1 and arg2:
foo arg1 arg2
# =&gt; Arguments work just like script arguments: arg1 arg2
# =&gt; And: arg1 arg2...
# =&gt; This is a function
# Return values can be obtained with $?
resultValue=$?
# More than 9 arguments are also possible by using braces, e.g. ${10}, ${11}, ...

# or simply
bar ()
{
    echo "Another way to declare functions!"
    return 0
}
# Call the function `bar` with no arguments:
bar # =&gt; Another way to declare functions!

# Calling your function
foo "My name is" $Name

# There are a lot of useful commands you should learn:
# prints last 10 lines of file.txt
tail -n 10 file.txt

# prints first 10 lines of file.txt
head -n 10 file.txt

# print file.txt's lines in sorted order
sort file.txt

# report or omit repeated lines, with -d it reports them
uniq -d file.txt

# prints only the first column before the ',' character
cut -d ',' -f 1 file.txt

# replaces every occurrence of 'okay' with 'great' in file.txt
# (regex compatible)
sed -i 's/okay/great/g' file.txt
# be aware that this -i flag means that file.txt will be changed
# -i or --in-place erase the input file (use --in-place=.backup to keep a back-up)

# print to stdout all lines of file.txt which match some regex
# The example prints lines which begin with "foo" and end in "bar"
grep "^foo.*bar$" file.txt

# pass the option "-c" to instead print the number of lines matching the regex
grep -c "^foo.*bar$" file.txt

# Other useful options are:
grep -r "^foo.*bar$" someDir/ # recursively `grep`
grep -n "^foo.*bar$" file.txt # give line numbers
grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files

# perform the same initial search, but filter out the lines containing "baz"
grep "^foo.*bar$" file.txt | grep -v "baz"

# if you literally want to search for the string,
# and not the regex, use `fgrep` (or `grep -F`)
fgrep "foobar" file.txt

# The `trap` command allows you to execute a command whenever your script
# receives a signal. Here, `trap` will execute `rm` if it receives any of the
# three listed signals.
trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM

# `sudo` is used to perform commands as the superuser
# usually it will ask interactively the password of superuser
NAME1=$(whoami)
NAME2=$(sudo whoami)
echo "Was $NAME1, then became more powerful $NAME2"

# Read Bash shell built-ins documentation with the bash `help` built-in:
help
help help
help for
help return
help source
help .

# Read Bash manpage documentation with `man`
apropos bash
man 1 bash
man bash

# Read info documentation with `info` (`?` for help)
apropos info | grep '^info.*('
man info
info info
info 5 info

# Read bash info documentation:
info bash
info bash 'Bash Features'
info bash 6
info --apropos bash
</code></pre>
<p>C:</p>
<pre><code class="lang-plaintext">// Single-line comments start with // - only available in C99 and later.

/*
Multi-line comments look like this. They work in C89 as well.
*/

/*
Multi-line comments don't nest /* Be careful */  // comment ends on this line...
*/ // ...not this one!

// Constants: #define &lt;keyword&gt;
// Constants are written in all-caps out of convention, not requirement
#define DAYS_IN_YEAR 365

// Enumeration constants are also ways to declare constants.
// All statements must end with a semicolon
enum days {SUN, MON, TUE, WED, THU, FRI, SAT};
// SUN gets 0, MON gets 1, TUE gets 2, etc.

// Enumeration values can also be specified
enum days {SUN = 1, MON, TUE, WED = 99, THU, FRI, SAT};
// MON gets 2 automatically, TUE gets 3, etc.
// WED get 99, THU gets 100, FRI gets 101, etc.

// Import headers with #include
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

// File names between &lt;angle brackets&gt; tell the compiler to look in your system
// libraries for the headers.
// For your own headers, use double quotes instead of angle brackets, and
// provide the path:
#include "my_header.h"         // local file
#include "../my_lib/my_lib_header.h" //relative path

// Declare function signatures in advance in a .h file, or at the top of
// your .c file.
void function_1();
int function_2(void);

// At a minimum, you must declare a 'function prototype' before its use in any function.
// Normally, prototypes are placed at the top of a file before any function definition.
int add_two_ints(int x1, int x2); // function prototype
// although `int add_two_ints(int, int);` is also valid (no need to name the args),
// it is recommended to name arguments in the prototype as well for easier inspection

// Function prototypes are not necessary if the function definition comes before
// any other function that calls that function. However, it's standard practice to
// always add the function prototype to a header file (*.h) and then #include that
// file at the top. This prevents any issues where a function might be called
// before the compiler knows of its existence, while also giving the developer a
// clean header file to share with the rest of the project.

// Your program's entry point is a function called "main". The return type can
// be anything, however most operating systems expect a return type of `int` for
// error code processing.
int main(void) {
  // your program
}

// The command line arguments used to run your program are also passed to main
// argc being the number of arguments - your program's name counts as 1
// argv is an array of character arrays - containing the arguments themselves
// argv[0] = name of your program, argv[1] = first argument, etc.
int main (int argc, char** argv)
{
  // print output using printf, for "print formatted"
  // %d is an integer, \n is a newline
  printf("%d\n", 0); // =&gt; Prints 0

  // take input using scanf
  // '&amp;' is used to define the location
  // where we want to store the input value
  int input;
  scanf("%d", &amp;input);

  ///////////////////////////////////////
  // Types
  ///////////////////////////////////////

  // Compilers that are not C99-compliant require that variables MUST be
  // declared at the top of the current block scope.
  // Compilers that ARE C99-compliant allow declarations near the point where
  // the value is used.
  // For the sake of the tutorial, variables are declared dynamically under
  // C99-compliant standards.

  // ints are usually 4 bytes (use the `sizeof` operator to check)
  int x_int = 0;

  // shorts are usually 2 bytes (use the `sizeof` operator to check)
  short x_short = 0;

  // chars are defined as the smallest addressable unit for a processor.
  // This is usually 1 byte, but for some systems it can be more (ex. for TMS320 from TI it's 2 bytes).
  char x_char = 0;
  char y_char = 'y'; // Char literals are quoted with ''

  // longs are often 4 to 8 bytes; long longs are guaranteed to be at least
  // 8 bytes
  long x_long = 0;
  long long x_long_long = 0;

  // floats are usually 32-bit floating point numbers
  float x_float = 0.0f; // 'f' suffix here denotes floating point literal

  // doubles are usually 64-bit floating-point numbers
  double x_double = 0.0; // real numbers without any suffix are doubles

  // integer types may be unsigned (greater than or equal to zero)
  unsigned short ux_short;
  unsigned int ux_int;
  unsigned long long ux_long_long;

  // chars inside single quotes are integers in machine's character set.
  '0'; // =&gt; 48 in the ASCII character set.
  'A'; // =&gt; 65 in the ASCII character set.

  // sizeof(T) gives you the size of a variable with type T in bytes
  // sizeof(obj) yields the size of the expression (variable, literal, etc.).
  printf("%zu\n", sizeof(int)); // =&gt; 4 (on most machines with 4-byte words)

  // If the argument of the `sizeof` operator is an expression, then its argument
  // is not evaluated (except VLAs (see below)).
  // The value it yields in this case is a compile-time constant.
  int a = 1;
  // size_t is an unsigned integer type of at least 2 bytes used to represent
  // the size of an object.
  size_t size = sizeof(a++); // a++ is not evaluated
  printf("sizeof(a++) = %zu where a = %d\n", size, a);
  // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)

  // Arrays must be initialized with a concrete size.
  char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes
  int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
  // (assuming 4-byte words)

  // You can initialize an array of twenty ints that all equal 0 thusly:
  int my_array[20] = {0};
  // where the "{0}" part is called an "array initializer".
  // All elements (if any) past the ones in the initializer are initialized to 0:
  int my_array[5] = {1, 2};
  // So my_array now has five elements, all but the first two of which are 0:
  // [1, 2, 0, 0, 0]
  // NOTE that you get away without explicitly declaring the size
  // of the array IF you initialize the array on the same line:
  int my_array[] = {0};
  // NOTE that, when not declaring the size, the size of the array is the number
  // of elements in the initializer. With "{0}", my_array is now of size one: [0]
  // To evaluate the size of the array at run-time, divide its byte size by the
  // byte size of its element type:
  size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]);
  // WARNING You should evaluate the size *before* you begin passing the array
  // to functions (see later discussion) because arrays get "downgraded" to
  // raw pointers when they are passed to functions (so the statement above
  // will produce the wrong result inside the function).

  // Indexing an array is like other languages -- or,
  // rather, other languages are like C
  my_array[0]; // =&gt; 0

  // Arrays are mutable; it's just memory!
  my_array[1] = 2;
  printf("%d\n", my_array[1]); // =&gt; 2

  // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
  // can be declared as well. The size of such an array need not be a compile
  // time constant:
  printf("Enter the array size: "); // ask the user for an array size
  int array_size;
  fscanf(stdin, "%d", &amp;array_size);
  int var_length_array[array_size]; // declare the VLA
  printf("sizeof array = %zu\n", sizeof var_length_array);

  // Example:
  // &gt; Enter the array size: 10
  // &gt; sizeof array = 40

  // Strings are just arrays of chars terminated by a NULL (0x00) byte,
  // represented in strings as the special character '\0'.
  // (We don't have to include the NULL byte in string literals; the compiler
  //  inserts it at the end of the array for us.)
  char a_string[20] = "This is a string";
  printf("%s\n", a_string); // %s formats a string

  printf("%d\n", a_string[16]); // =&gt; 0
  // i.e., byte #17 is 0 (as are 18, 19, and 20)

  // If we have characters between single quotes, that's a character literal.
  // It's of type `int`, and *not* `char` (for historical reasons).
  int cha = 'a'; // fine
  char chb = 'a'; // fine too (implicit conversion from int to char)

  // Multi-dimensional arrays:
  int multi_array[2][5] = {
    {1, 2, 3, 4, 5},
    {6, 7, 8, 9, 0}
  };
  // access elements:
  int array_int = multi_array[0][2]; // =&gt; 3

  ///////////////////////////////////////
  // Operators
  ///////////////////////////////////////

  // Shorthands for multiple declarations:
  int i1 = 1, i2 = 2;
  float f1 = 1.0, f2 = 2.0;

  int b, c;
  b = c = 0;

  // Arithmetic is straightforward
  i1 + i2; // =&gt; 3
  i2 - i1; // =&gt; 1
  i2 * i1; // =&gt; 2
  i1 / i2; // =&gt; 0 (0.5, but truncated towards 0)

  // You need to cast at least one integer to float to get a floating-point result
  (float)i1 / i2; // =&gt; 0.5f
  i1 / (double)i2; // =&gt; 0.5 // Same with double
  f1 / f2; // =&gt; 0.5, plus or minus epsilon

  // Floating-point numbers are defined by IEEE 754, thus cannot store perfectly
  // exact values. For instance, the following does not produce expected results
  // because 0.1 might actually be 0.099999999999 inside the computer, and 0.3
  // might be stored as 0.300000000001.
  (0.1 + 0.1 + 0.1) != 0.3; // =&gt; 1 (true)
  // and it is NOT associative due to reasons mentioned above.
  1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // =&gt; 1 (true)
  // this notation is scientific notations for numbers: 1e123 = 1*10^123

  // It is important to note that most all systems have used IEEE 754 to
  // represent floating points. Even python, used for scientific computing,
  // eventually calls C which uses IEEE 754. It is mentioned this way not to
  // indicate that this is a poor implementation, but instead as a warning
  // that when doing floating point comparisons, a little bit of error (epsilon)
  // needs to be considered.

  // Modulo is there as well, but be careful if arguments are negative
  11 % 3;    // =&gt; 2 as 11 = 2 + 3*x (x=3)
  (-11) % 3; // =&gt; -2, as one would expect
  11 % (-3); // =&gt; 2 and not -2, and it's quite counter intuitive

  // Comparison operators are probably familiar, but
  // there is no Boolean type in C. We use ints instead.
  // (C99 introduced the _Bool type provided in stdbool.h)
  // 0 is false, anything else is true. (The comparison
  // operators always yield 0 or 1.)
  3 == 2; // =&gt; 0 (false)
  3 != 2; // =&gt; 1 (true)
  3 &gt; 2;  // =&gt; 1
  3 &lt; 2;  // =&gt; 0
  2 &lt;= 2; // =&gt; 1
  2 &gt;= 2; // =&gt; 1

  // C is not Python - comparisons do NOT chain.
  // Warning: The line below will compile, but it means `(0 &lt; a) &lt; 2`.
  // This expression is always true, because (0 &lt; a) could be either 1 or 0.
  // In this case it's 1, because (0 &lt; 1).
  int between_0_and_2 = 0 &lt; a &lt; 2;
  // Instead use:
  int between_0_and_2 = 0 &lt; a &amp;&amp; a &lt; 2;

  // Logic works on ints
  !3; // =&gt; 0 (Logical not)
  !0; // =&gt; 1
  1 &amp;&amp; 1; // =&gt; 1 (Logical and)
  0 &amp;&amp; 1; // =&gt; 0
  0 || 1; // =&gt; 1 (Logical or)
  0 || 0; // =&gt; 0

  // Conditional ternary expression ( ? : )
  int e = 5;
  int f = 10;
  int z;
  z = (e &gt; f) ? e : f; // =&gt; 10 "if e &gt; f return e, else return f."

  // Increment and decrement operators:
  int j = 0;
  int s = j++; // Return j THEN increase j. (s = 0, j = 1)
  s = ++j; // Increase j THEN return j. (s = 2, j = 2)
  // same with j-- and --j

  // Bitwise operators!
  ~0x0F; // =&gt; 0xFFFFFFF0 (bitwise negation, "1's complement", example result for 32-bit int)
  0x0F &amp; 0xF0; // =&gt; 0x00 (bitwise AND)
  0x0F | 0xF0; // =&gt; 0xFF (bitwise OR)
  0x04 ^ 0x0F; // =&gt; 0x0B (bitwise XOR)
  0x01 &lt;&lt; 1; // =&gt; 0x02 (bitwise left shift (by 1))
  0x02 &gt;&gt; 1; // =&gt; 0x01 (bitwise right shift (by 1))

  // Be careful when shifting signed integers - the following are undefined:
  // - shifting into the sign bit of a signed integer (int a = 1 &lt;&lt; 31)
  // - left-shifting a negative number (int a = -1 &lt;&lt; 2)
  // - shifting by an offset which is &gt;= the width of the type of the LHS:
  //   int a = 1 &lt;&lt; 32; // UB if int is 32 bits wide

  ///////////////////////////////////////
  // Control Structures
  ///////////////////////////////////////

  if (0) {
    printf("I am never run\n");
  } else if (0) {
    printf("I am also never run\n");
  } else {
    printf("I print\n");
  }

  // While loops exist
  int ii = 0;
  while (ii &lt; 10) { //ANY value less than ten is true.
    printf("%d, ", ii++); // ii++ increments ii AFTER using its current value.
  } // =&gt; prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "

  printf("\n");

  int kk = 0;
  do {
    printf("%d, ", kk);
  } while (++kk &lt; 10); // ++kk increments kk BEFORE using its current value.
  // =&gt; prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "

  printf("\n");

  // For loops too
  int jj;
  for (jj=0; jj &lt; 10; jj++) {
    printf("%d, ", jj);
  } // =&gt; prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "

  printf("\n");

  // *****NOTES*****:
  // Loops and Functions MUST have a body. If no body is needed:
  int i;
  for (i = 0; i &lt;= 5; i++) {
    ; // use semicolon to act as the body (null statement)
  }
  // Or
  for (i = 0; i &lt;= 5; i++);

  // branching with multiple choices: switch()
  switch (a) {
  case 0: // labels need to be integral *constant* expressions (such as enums)
    printf("Hey, 'a' equals 0!\n");
    break; // if you don't break, control flow falls over labels
  case 1:
    printf("Huh, 'a' equals 1!\n");
    break;
    // Be careful - without a "break", execution continues until the
    // next "break" is reached.
  case 3:
  case 4:
    printf("Look at that.. 'a' is either 3, or 4\n");
    break;
  default:
    // if `some_integral_expression` didn't match any of the labels
    fputs("Error!\n", stderr);
    exit(-1);
    break;
  }
  /*
    Using "goto" in C
  */
  typedef enum { false, true } bool;
  // for C don't have bool as data type before C99 :(
  bool disaster = false;
  int i, j;
  for(i=0; i&lt;100; ++i)
  for(j=0; j&lt;100; ++j)
  {
    if((i + j) &gt;= 150)
        disaster = true;
    if(disaster)
        goto error;  // exit both for loops
  }
  error: // this is a label that you can "jump" to with "goto error;"
  printf("Error occurred at i = %d &amp; j = %d.\n", i, j);
  /*
    https://ideone.com/GuPhd6
    this will print out "Error occurred at i = 51 &amp; j = 99."
  */
  /*
    it is generally considered bad practice to do so, except if
    you really know what you are doing. See
    https://en.wikipedia.org/wiki/Spaghetti_code#Meaning
  */

  ///////////////////////////////////////
  // Typecasting
  ///////////////////////////////////////

  // Every value in C has a type, but you can cast one value into another type
  // if you want (with some constraints).

  int x_hex = 0x01; // You can assign vars with hex literals
                    // binary is not in the standard, but allowed by some
                    // compilers (x_bin = 0b0010010110)

  // Casting between types will attempt to preserve their numeric values
  printf("%d\n", x_hex); // =&gt; Prints 1
  printf("%d\n", (short) x_hex); // =&gt; Prints 1
  printf("%d\n", (char) x_hex); // =&gt; Prints 1

  // If you assign a value greater than a types max val, it will rollover
  // without warning.
  printf("%d\n", (unsigned char) 257); // =&gt; 1 (Max char = 255 if char is 8 bits long)

  // For determining the max value of a `char`, a `signed char` and an `unsigned char`,
  // respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from &lt;limits.h&gt;

  // Integral types can be cast to floating-point types, and vice-versa.
  printf("%f\n", (double) 100); // %f always formats a double...
  printf("%f\n", (float)  100); // ...even with a float.
  printf("%d\n", (char)100.0);

  ///////////////////////////////////////
  // Pointers
  ///////////////////////////////////////

  // A pointer is a variable declared to store a memory address. Its declaration will
  // also tell you the type of data it points to. You can retrieve the memory address
  // of your variables, then mess with them.

  int x = 0;
  printf("%p\n", (void *)&amp;x); // Use &amp; to retrieve the address of a variable
  // (%p formats an object pointer of type void *)
  // =&gt; Prints some address in memory;

  // Pointers start with * in their declaration
  int *px, not_a_pointer; // px is a pointer to an int
  px = &amp;x; // Stores the address of x in px
  printf("%p\n", (void *)px); // =&gt; Prints some address in memory
  printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
  // =&gt; Prints "8, 4" on a typical 64-bit system

  // To retrieve the value at the address a pointer is pointing to,
  // put * in front to dereference it.
  // Note: yes, it may be confusing that '*' is used for _both_ declaring a
  // pointer and dereferencing it.
  printf("%d\n", *px); // =&gt; Prints 0, the value of x

  // You can also change the value the pointer is pointing to.
  // We'll have to wrap the dereference in parenthesis because
  // ++ has a higher precedence than *.
  (*px)++; // Increment the value px is pointing to by 1
  printf("%d\n", *px); // =&gt; Prints 1
  printf("%d\n", x); // =&gt; Prints 1

  // Arrays are a good way to allocate a contiguous block of memory
  int x_array[20]; //declares array of size 20 (cannot change size)
  int xx;
  for (xx = 0; xx &lt; 20; xx++) {
    x_array[xx] = 20 - xx;
  } // Initialize x_array to 20, 19, 18,... 2, 1

  // Declare a pointer of type int and initialize it to point to x_array
  int* x_ptr = x_array;
  // x_ptr now points to the first element in the array (the integer 20).
  // This works because arrays often decay into pointers to their first element.
  // For example, when an array is passed to a function or is assigned to a pointer,
  // it decays into (implicitly converted to) a pointer.
  // Exceptions: when the array is the argument of the `&amp;` (address-of) operator:
  int arr[10];
  int (*ptr_to_arr)[10] = &amp;arr; // &amp;arr is NOT of type `int *`!
  // It's of type "pointer to array" (of ten `int`s).
  // or when the array is a string literal used for initializing a char array:
  char otherarr[] = "foobarbazquirk";
  // or when it's the argument of the `sizeof` or `alignof` operator:
  int arraythethird[10];
  int *ptr = arraythethird; // equivalent with int *ptr = &amp;arr[0];
  printf("%zu, %zu\n", sizeof(arraythethird), sizeof(ptr));
  // probably prints "40, 4" or "40, 8"

  // Pointers are incremented and decremented based on their type
  // (this is called pointer arithmetic)
  printf("%d\n", *(x_ptr + 1)); // =&gt; Prints 19
  printf("%d\n", x_array[1]); // =&gt; Prints 19

  // You can also dynamically allocate contiguous blocks of memory with the
  // standard library function malloc, which takes one argument of type size_t
  // representing the number of bytes to allocate (usually from the heap, although this
  // may not be true on e.g. embedded systems - the C standard says nothing about it).
  int *my_ptr = malloc(sizeof(*my_ptr) * 20);
  for (xx = 0; xx &lt; 20; xx++) {
    *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
  } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)

  // Be careful passing user-provided values to malloc! If you want
  // to be safe, you can use calloc instead (which, unlike malloc, also zeros out the memory)
  int* my_other_ptr = calloc(20, sizeof(int));

  // Note that there is no standard way to get the length of a
  // dynamically allocated array in C. Because of this, if your arrays are
  // going to be passed around your program a lot, you need another variable
  // to keep track of the number of elements (size) of an array. See the
  // functions section for more info.
  size_t size = 10;
  int *my_arr = calloc(size, sizeof(int));
  // Add an element to the array
  size++;
  my_arr = realloc(my_arr, sizeof(int) * size);
  if (my_arr == NULL) {
    //Remember to check for realloc failure!
    return
  }
  my_arr[10] = 5;

  // Dereferencing memory that you haven't allocated gives
  // "unpredictable results" - the program is said to invoke "undefined behavior"
  printf("%d\n", *(my_ptr + 21)); // =&gt; Prints who-knows-what? It may even crash.

  // When you're done with a malloc'd block of memory, you need to free it,
  // or else no one else can use it until your program terminates
  // (this is called a "memory leak"):
  free(my_ptr);

  // Strings are arrays of char, but they are usually represented as a
  // pointer-to-char (which is a pointer to the first element of the array).
  // It's good practice to use `const char *' when referring to a string literal,
  // since string literals shall not be modified (i.e. "foo"[0] = 'a' is ILLEGAL.)
  const char *my_str = "This is my very own string literal";
  printf("%c\n", *my_str); // =&gt; 'T'

  // This is not the case if the string is an array
  // (potentially initialized with a string literal)
  // that resides in writable memory, as in:
  char foo[] = "foo";
  foo[0] = 'a'; // this is legal, foo now contains "aoo"

  function_1();
} // end main function

///////////////////////////////////////
// Functions
///////////////////////////////////////

// Function declaration syntax:
// &lt;return type&gt; &lt;function name&gt;(&lt;args&gt;)

int add_two_ints(int x1, int x2)
{
  return x1 + x2; // Use return to return a value
}

/*
Functions are call by value. When a function is called, the arguments passed to
the function are copies of the original arguments (except arrays). Anything you
do to the arguments in the function do not change the value of the original
argument where the function was called.

Use pointers if you need to edit the original argument values (arrays are always
passed in as pointers).

Example: in-place string reversal
*/

// A void function returns no value
void str_reverse(char *str_in)
{
  char tmp;
  size_t ii = 0;
  size_t len = strlen(str_in); // `strlen()` is part of the c standard library
                               // NOTE: length returned by `strlen` DOESN'T
                               //       include the terminating NULL byte ('\0')
  // in C99 and newer versions, you can directly declare loop control variables
  // in the loop's parentheses. e.g., `for (size_t ii = 0; ...`
  for (ii = 0; ii &lt; len / 2; ii++) {
    tmp = str_in[ii];
    str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
    str_in[len - ii - 1] = tmp;
  }
}
//NOTE: string.h header file needs to be included to use strlen()

/*
char c[] = "This is a test.";
str_reverse(c);
printf("%s\n", c); // =&gt; ".tset a si sihT"
*/
/*
as we can return only one variable
to change values of more than one variables we use call by reference
*/
void swapTwoNumbers(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
/*
int first = 10;
int second = 20;
printf("first: %d\nsecond: %d\n", first, second);
swapTwoNumbers(&amp;first, &amp;second);
printf("first: %d\nsecond: %d\n", first, second);
// values will be swapped
*/

// Return multiple values.
// C does not allow for returning multiple values with the return statement. If
// you would like to return multiple values, then the caller must pass in the
// variables where they would like the returned values to go. These variables must
// be passed in as pointers such that the function can modify them.
int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3)
{
    if(array_of_3 == NULL)
        return 0; //return error code (false)

    //de-reference the pointer so we modify its value
   *ret1 = array_of_3[0];
   *ret2 = array_of_3[1];
   *ret3 = array_of_3[2];

   return 1; //return error code (true)
}

/*
With regards to arrays, they will always be passed to functions
as pointers. Even if you statically allocate an array like `arr[10]`,
it still gets passed as a pointer to the first element in any function calls.
Again, there is no standard way to get the size of a dynamically allocated
array in C.
*/
// Size must be passed!
// Otherwise, this function has no way of knowing how big the array is.
void printIntArray(int *arr, size_t size) {
    int i;
    for (i = 0; i &lt; size; i++) {
        printf("arr[%d] is: %d\n", i, arr[i]);
    }
}
/*
int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int size = 10;
printIntArray(my_arr, size);
// will print "arr[0] is: 1" etc
*/

// if referring to external variables outside function, you should use the extern keyword.
int i = 0;
void testFunc() {
  extern int i; //i here is now using external variable i
}

// make external variables private to source file with static:
static int j = 0; //other files using testFunc2() cannot access variable j
void testFunc2() {
  extern int j;
}
// The static keyword makes a variable inaccessible to code outside the
// compilation unit. (On almost all systems, a "compilation unit" is a .c
// file.) static can apply both to global (to the compilation unit) variables,
// functions, and function-local variables. When using static with
// function-local variables, the variable is effectively global and retains its
// value across function calls, but is only accessible within the function it
// is declared in. Additionally, static variables are initialized to 0 if not
// declared with some other starting value.
//**You may also declare functions as static to make them private**

///////////////////////////////////////
// User-defined types and structs
///////////////////////////////////////

// Typedefs can be used to create type aliases
typedef int my_type;
my_type my_type_var = 0;

// Structs are just collections of data, the members are allocated sequentially,
// in the order they are written:
struct rectangle {
  int width;
  int height;
};

// It's not generally true that
// sizeof(struct rectangle) == sizeof(int) + sizeof(int)
// due to potential padding between the structure members (this is for alignment
// reasons). [1]

void function_1()
{
  struct rectangle my_rec = { 1, 2 }; // Fields can be initialized immediately

  // Access struct members with .
  my_rec.width = 10;
  my_rec.height = 20;

  // You can declare pointers to structs
  struct rectangle *my_rec_ptr = &amp;my_rec;

  // Use dereferencing to set struct pointer members...
  (*my_rec_ptr).width = 30;

  // ... or even better: prefer the -&gt; shorthand for the sake of readability
  my_rec_ptr-&gt;height = 10; // Same as (*my_rec_ptr).height = 10;
}

// You can apply a typedef to a struct for convenience
typedef struct rectangle rect;

int area(rect r)
{
  return r.width * r.height;
}

// Typedefs can also be defined right during struct definition
typedef struct {
  int width;
  int height;
} rect;
// Like before, doing this means one can type
rect r;
// instead of having to type
struct rectangle r;

// if you have large structs, you can pass them "by pointer" to avoid copying
// the whole struct:
int areaptr(const rect *r)
{
  return r-&gt;width * r-&gt;height;
}

///////////////////////////////////////
// Function pointers
///////////////////////////////////////
/*
At run time, functions are located at known memory addresses. Function pointers are
much like any other pointer (they just store a memory address), but can be used
to invoke functions directly, and to pass handlers (or callback functions) around.
However, definition syntax may be initially confusing.

Example: use str_reverse from a pointer
*/
void str_reverse_through_pointer(char *str_in) {
  // Define a function pointer variable, named f.
  void (*f)(char *); // Signature should exactly match the target function.
  f = &amp;str_reverse; // Assign the address for the actual function (determined at run time)
  // f = str_reverse; would work as well - functions decay into pointers, similar to arrays
  (*f)(str_in); // Just calling the function through the pointer
  // f(str_in); // That's an alternative but equally valid syntax for calling it.
}

/*
As long as function signatures match, you can assign any function to the same pointer.
Function pointers are usually typedef'd for simplicity and readability, as follows:
*/

typedef void (*my_fnp_type)(char *);

// Then used when declaring the actual pointer variable:
// ...
// my_fnp_type f;


/////////////////////////////
// Printing characters with printf()
/////////////////////////////

//Special characters:
/*
'\a'; // alert (bell) character
'\n'; // newline character
'\t'; // tab character (left justifies text)
'\v'; // vertical tab
'\f'; // new page (form feed)
'\r'; // carriage return
'\b'; // backspace character
'\0'; // NULL character. Usually put at end of strings in C.
//   hello\n\0. \0 used by convention to mark end of string.
'\\'; // backslash
'\?'; // question mark
'\''; // single quote
'\"'; // double quote
'\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character
'\0oo'; // octal number. Example: '\013' = vertical tab character

//print formatting:
"%d";    // integer
"%3d";   // integer with minimum of length 3 digits (right justifies text)
"%s";    // string
"%f";    // float
"%ld";   // long
"%3.2f"; // minimum 3 digits left and 2 digits right decimal float
"%7.4s"; // (can do with strings too)
"%c";    // char
"%p";    // pointer. NOTE: need to (void *)-cast the pointer, before passing
         //                it as an argument to `printf`.
"%x";    // hexadecimal
"%o";    // octal
"%%";    // prints %
*/

///////////////////////////////////////
// Order of Evaluation
///////////////////////////////////////

// From top to bottom, top has higher precedence
//---------------------------------------------------//
//        Operators                  | Associativity //
//---------------------------------------------------//
// () [] -&gt; .                        | left to right //
// ! ~ ++ -- + = *(type) sizeof      | right to left //
// * / %                             | left to right //
// + -                               | left to right //
// &lt;&lt; &gt;&gt;                             | left to right //
// &lt; &lt;= &gt; &gt;=                         | left to right //
// == !=                             | left to right //
// &amp;                                 | left to right //
// ^                                 | left to right //
// |                                 | left to right //
// &amp;&amp;                                | left to right //
// ||                                | left to right //
// ?:                                | right to left //
// = += -= *= /= %= &amp;= ^= |= &lt;&lt;= &gt;&gt;= | right to left //
// ,                                 | left to right //
//---------------------------------------------------//

/******************************* Header Files **********************************

Header files are an important part of C as they allow for the connection of C
source files and can simplify code and definitions by separating them into
separate files.

Header files are syntactically similar to C source files but reside in ".h"
files. They can be included in your C source file by using the preprocessor
directive #include "example.h", given that example.h exists in the same directory
as the C file.
*/

/* A safe guard to prevent the header from being defined too many times. This */
/* happens in the case of circle dependency, the contents of the header is    */
/* already defined.                                                           */
#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */
#define EXAMPLE_H /* Define the macro EXAMPLE_H. */

/* Other headers can be included in headers and therefore transitively */
/* included into files that include this header.                       */
#include &lt;string.h&gt;

/* Like for c source files, macros can be defined in headers */
/* and used in files that include this header file.          */
#define EXAMPLE_NAME "Dennis Ritchie"

/* Function macros can also be defined.  */
#define ADD(a, b) ((a) + (b))

/* Notice the parenthesis surrounding the arguments -- this is important to   */
/* ensure that a and b don't get expanded in an unexpected way (e.g. consider */
/* MUL(x, y) (x * y); MUL(1 + 2, 3) would expand to (1 + 2 * 3), yielding an  */
/* incorrect result)                                                          */

/* Structs and typedefs can be used for consistency between files. */
typedef struct Node
{
    int val;
    struct Node *next;
} Node;

/* So can enumerations. */
enum traffic_light_state {GREEN, YELLOW, RED};

/* Function prototypes can also be defined here for use in multiple files,  */
/* but it is bad practice to define the function in the header. Definitions */
/* should instead be put in a C file.                                       */
Node createLinkedList(int *vals, int len);

/* Beyond the above elements, other definitions should be left to a C source */
/* file. Excessive includes or definitions should also not be contained in   */
/* a header file but instead put into separate headers or a C file.          */

#endif /* End of the if preprocessor directive. */
</code></pre>
<p>C#:</p>
<pre><code class="lang-plaintext">// Single-line comments start with //

/*
Multi-line comments look like this
*/

/// &lt;summary&gt;
/// This is an XML documentation comment which can be used to generate external
/// documentation or provide context help within an IDE
/// &lt;/summary&gt;
/// &lt;param name="firstParam"&gt;This is some parameter documentation for firstParam&lt;/param&gt;
/// &lt;returns&gt;Information on the returned value of a function&lt;/returns&gt;
public void MethodOrClassOrOtherWithParsableHelp(string firstParam) { }

// Specify the namespaces this source code will be using
// The namespaces below are all part of the standard .NET Framework Class Library
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.IO;

// But this one is not:
using System.Data.Entity;
// In order to be able to use it, you need to add a dll reference
// This can be done with the NuGet package manager: `Install-Package EntityFramework`

// Namespaces define scope to organize code into "packages" or "modules"
// Using this code from another source file: using Learning.CSharp;

// You can also do this in C# 10, it is called file-scoped namespaces.
// namespace Learning.CSharp;

namespace Learning.CSharp
{
    // Each .cs file should at least contain a class with the same name as the file.
    // You're allowed to do otherwise, but shouldn't for sanity.
    public class LearnCSharp
    {
        // BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before
        public static void Syntax()
        {
            // Use Console.WriteLine to print lines
            Console.WriteLine("Hello World");
            Console.WriteLine(
                "Integer: " + 10 +
                " Double: " + 3.14 +
                " Boolean: " + true);

            // To print without a new line, use Console.Write
            Console.Write("Hello ");
            Console.Write("World");

            ///////////////////////////////////////////////////
            // Types &amp; Variables
            //
            // Declare a variable using &lt;type&gt; &lt;name&gt;
            ///////////////////////////////////////////////////

            // Sbyte - Signed 8-bit integer
            // (-128 &lt;= sbyte &lt;= 127)
            sbyte fooSbyte = 100;

            // Byte - Unsigned 8-bit integer
            // (0 &lt;= byte &lt;= 255)
            byte fooByte = 100;

            // Short - 16-bit integer
            // Signed - (-32,768 &lt;= short &lt;= 32,767)
            // Unsigned - (0 &lt;= ushort &lt;= 65,535)
            short fooShort = 10000;
            ushort fooUshort = 10000;

            // Integer - 32-bit integer
            int fooInt = 1; // (-2,147,483,648 &lt;= int &lt;= 2,147,483,647)
            uint fooUint = 1; // (0 &lt;= uint &lt;= 4,294,967,295)

            // Long - 64-bit integer
            long fooLong = 100000L; // (-9,223,372,036,854,775,808 &lt;= long &lt;= 9,223,372,036,854,775,807)
            ulong fooUlong = 100000L; // (0 &lt;= ulong &lt;= 18,446,744,073,709,551,615)
            // Numbers default to being int or uint depending on size.
            // L is used to denote that this variable value is of type long or ulong

            // Double - Double-precision 64-bit IEEE 754 Floating Point
            double fooDouble = 123.4; // Precision: 15-16 digits

            // Float - Single-precision 32-bit IEEE 754 Floating Point
            float fooFloat = 234.5f; // Precision: 7 digits
            // f is used to denote that this variable value is of type float

            // Decimal - a 128-bits data type, with more precision than other floating-point types,
            // suited for financial and monetary calculations
            decimal fooDecimal = 150.3m;

            // Boolean - true &amp; false
            bool fooBoolean = true; // or false

            // Char - A single 16-bit Unicode character
            char fooChar = 'A';

            // Strings -- unlike the previous base types which are all value types,
            // a string is a reference type. That is, you can set it to null
            string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)";
            Console.WriteLine(fooString);

            // You can access each character of the string with an indexer:
            char charFromString = fooString[1]; // =&gt; 'e'
            // Strings are immutable: you can't do fooString[1] = 'X';

            // Compare strings with current culture, ignoring case
            string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);

            // Formatting, based on sprintf
            string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);

            // Dates &amp; Formatting
            DateTime fooDate = DateTime.Now;
            Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));

            // Verbatim String
            // You can use the @ symbol before a string literal to escape all characters in the string
            string path = "C:\\Users\\User\\Desktop";
            string verbatimPath = @"C:\Users\User\Desktop";
            Console.WriteLine(path == verbatimPath);  // =&gt; true

            // You can split a string over two lines with the @ symbol. To escape " use ""
            string bazString = @"Here's some stuff
on a new line! ""Wow!"", the masses cried";

            // Use const or read-only to make a variable immutable
            // const values are calculated at compile time
            const int HoursWorkPerWeek = 9001;

            ///////////////////////////////////////////////////
            // Data Structures
            ///////////////////////////////////////////////////

            // Arrays - zero indexed
            // The array size must be decided upon declaration
            // The format for declaring an array is
            // &lt;datatype&gt;[] &lt;var name&gt; = new &lt;datatype&gt;[&lt;array size&gt;];
            int[] intArray = new int[10];

            // Another way to declare &amp; initialize an array
            int[] y = { 9000, 1000, 1337 };

            // Indexing an array - Accessing an element
            Console.WriteLine("intArray @ 0: " + intArray[0]);
            // Arrays are mutable.
            intArray[1] = 1;

            // Lists
            // Lists are used more frequently than arrays as they are more flexible
            // The format for declaring a list is
            // List&lt;datatype&gt; &lt;var name&gt; = new List&lt;datatype&gt;();
            List&lt;int&gt; intList = new List&lt;int&gt;();
            List&lt;string&gt; stringList = new List&lt;string&gt;();
            List&lt;int&gt; z = new List&lt;int&gt; { 9000, 1000, 1337 }; // initialize
            // The &lt;&gt; are for generics - Check out the cool stuff section

            // Lists don't default to a value;
            // A value must be added before accessing the index
            intList.Add(1);
            Console.WriteLine("intList at 0: " + intList[0]);

            // Other data structures to check out:
            // Stack/Queue
            // Dictionary (an implementation of a hash map)
            // HashSet
            // Read-only Collections
            // Tuple (.NET 4+)

            ///////////////////////////////////////
            // Operators
            ///////////////////////////////////////
            Console.WriteLine("\n-&gt;Operators");

            int i1 = 1, i2 = 2; // Shorthand for multiple declarations

            // Arithmetic is straightforward
            Console.WriteLine(i1 + i2 - i1 * 3 / 7); // =&gt; 3

            // Modulo
            Console.WriteLine("11%3 = " + (11 % 3)); // =&gt; 2

            // Comparison operators
            Console.WriteLine("3 == 2? " + (3 == 2)); // =&gt; false
            Console.WriteLine("3 != 2? " + (3 != 2)); // =&gt; true
            Console.WriteLine("3 &gt; 2? " + (3 &gt; 2)); // =&gt; true
            Console.WriteLine("3 &lt; 2? " + (3 &lt; 2)); // =&gt; false
            Console.WriteLine("2 &lt;= 2? " + (2 &lt;= 2)); // =&gt; true
            Console.WriteLine("2 &gt;= 2? " + (2 &gt;= 2)); // =&gt; true

            // Bitwise operators!
            /*
            ~       Unary bitwise complement
            &lt;&lt;      Signed left shift
            &gt;&gt;      Signed right shift
            &amp;       Bitwise AND
            ^       Bitwise exclusive OR
            |       Bitwise inclusive OR
            */

            // Incrementing
            int i = 0;
            Console.WriteLine("\n-&gt;Inc/Dec-rement");
            Console.WriteLine(i++); //Prints "0", i = 1. Post-Increment
            Console.WriteLine(++i); //Prints "2", i = 2. Pre-Increment
            Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrement
            Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrement

            ///////////////////////////////////////
            // Control Structures
            ///////////////////////////////////////
            Console.WriteLine("\n-&gt;Control Structures");

            // If statements are C-like
            int j = 10;
            if (j == 10)
            {
                Console.WriteLine("I get printed");
            }
            else if (j &gt; 10)
            {
                Console.WriteLine("I don't");
            }
            else
            {
                Console.WriteLine("I also don't");
            }

            // Ternary operators
            // A simple if/else can be written as follows
            // &lt;condition&gt; ? &lt;true&gt; : &lt;false&gt;
            int toCompare = 17;
            string isTrue = toCompare == 17 ? "True" : "False";

            // While loop
            int fooWhile = 0;
            while (fooWhile &lt; 100)
            {
                // Iterated 100 times, fooWhile 0-&gt;99
                fooWhile++;
            }

            // Do While Loop
            int fooDoWhile = 0;
            do
            {
                // Start iteration 100 times, fooDoWhile 0-&gt;99
                if (false)
                    continue; // skip the current iteration

                fooDoWhile++;

                if (fooDoWhile == 50)
                    break; // breaks from the loop completely

            } while (fooDoWhile &lt; 100);

            // for loop structure =&gt; for(&lt;start_statement&gt;; &lt;conditional&gt;; &lt;step&gt;)
            for (int fooFor = 0; fooFor &lt; 10; fooFor++)
            {
                // Iterated 10 times, fooFor 0-&gt;9
            }

            // For Each Loop
            // foreach loop structure =&gt; foreach(&lt;iteratorType&gt; &lt;iteratorName&gt; in &lt;enumerable&gt;)
            // The foreach loop loops over any object implementing IEnumerable or IEnumerable&lt;T&gt;
            // All the collection types (Array, List, Dictionary...) in the .NET framework
            // implement one or both of these interfaces.
            // (The ToCharArray() could be removed, because a string also implements IEnumerable)
            foreach (char character in "Hello World".ToCharArray())
            {
                // Iterated over all the characters in the string
            }

            // Switch Case
            // A switch works with byte, short, char, and int data types.
            // It also works with enumerated types (discussed in Enum Types),
            // the String class, and a few special classes that wrap
            // primitive types: Character, Byte, Short, and Integer.
            int month = 3;
            string monthString;
            switch (month)
            {
                case 1:
                    monthString = "January";
                    break;
                case 2:
                    monthString = "February";
                    break;
                case 3:
                    monthString = "March";
                    break;
                // You can assign more than one case to an action
                // But you can't add an action without a break before another case
                // (if you want to do this, you would have to explicitly add a goto case x)
                case 6:
                case 7:
                case 8:
                    monthString = "Summer time!!";
                    break;
                default:
                    monthString = "Some other month";
                    break;
            }

            ///////////////////////////////////////
            // Converting Data Types And Typecasting
            ///////////////////////////////////////

            // Converting data

            // Convert String To Integer
            // this will throw a FormatException on failure
            int.Parse("123"); // returns an integer version of "123"

            // TryParse will default to the type's default value on failure
            // in this case 0
            int tryInt;
            if (int.TryParse("123", out tryInt)) // Function is boolean
                Console.WriteLine(tryInt);       // 123

            // Convert Integer To String
            // The Convert class has a number of methods to facilitate conversions

            // String to int

            // Better
            bool result = int.TryParse(string, out var integer)
            int.Parse(string);

            // Not recommended
            Convert.ToString(123);

            // Int to string
            tryInt.ToString();

            // Casting
            // Cast decimal 15 to an int
            // and then implicitly cast to long
            long x = (int) 15M;
        }

        ///////////////////////////////////////
        // CLASSES - see definitions at end of file
        ///////////////////////////////////////
        public static void Classes()
        {
            // See Declaration of objects at end of file

            // Use new to instantiate a class
            Bicycle trek = new Bicycle();

            // Call object methods
            trek.SpeedUp(3); // You should always use setter and getter methods
            trek.Cadence = 100;

            // ToString is a convention to display the value of this Object.
            Console.WriteLine("trek info: " + trek.Info());

            // Instantiate a new Penny Farthing
            PennyFarthing funbike = new PennyFarthing(1, 10);
            Console.WriteLine("funbike info: " + funbike.Info());

            Console.Read();
        } // End main method

        // Available in C# 9 and later, this is basically syntactic sugar for a class. Records are immutable*.
        public record ARecord(string Csharp);

        // CONSOLE ENTRY - A console application must have a main method as an entry point
        public static void Main(string[] args)
        {
            OtherInterestingFeatures();
        }

        //
        // INTERESTING FEATURES
        //

        // DEFAULT METHOD SIGNATURES

        public // Visibility
        static // Allows for direct call on class without object
        int // Return Type,
        MethodSignatures(
            int maxCount, // First variable, expects an int
            int count = 0, // will default the value to 0 if not passed in
            int another = 3,
            params string[] otherParams // captures all other parameters passed to method
        )
        {
            return -1;
        }

        // Methods can have the same name, as long as the signature is unique
        // A method that differs only in return type is not unique
        public static void MethodSignatures(
            ref int maxCount, // Pass by reference
            out int count)
        {
            // the argument passed in as 'count' will hold the value of 15 outside of this function
            count = 15; // out param must be assigned before control leaves the method
        }

        // GENERICS
        // The classes for TKey and TValue is specified by the user calling this function.
        // This method emulates Python's dict.setdefault()
        public static TValue SetDefault&lt;TKey, TValue&gt;(
            IDictionary&lt;TKey, TValue&gt; dictionary,
            TKey key,
            TValue defaultItem)
        {
            TValue result;
            if (!dictionary.TryGetValue(key, out result))
                return dictionary[key] = defaultItem;
            return result;
        }

        // You can narrow down the objects that are passed in
        public static void IterateAndPrint&lt;T&gt;(T toPrint) where T: IEnumerable&lt;int&gt;
        {
            // We can iterate, since T is a IEnumerable
            foreach (var item in toPrint)
                // Item is an int
                Console.WriteLine(item.ToString());
        }

        // YIELD
        // Usage of the "yield" keyword indicates that the method it appears in is an Iterator
        // (this means you can use it in a foreach loop)
        public static IEnumerable&lt;int&gt; YieldCounter(int limit = 10)
        {
            for (var i = 0; i &lt; limit; i++)
                yield return i;
        }

        // which you would call like this :
        public static void PrintYieldCounterToConsole()
        {
            foreach (var counter in YieldCounter())
                Console.WriteLine(counter);
        }

        // you can use more than one "yield return" in a method
        public static IEnumerable&lt;int&gt; ManyYieldCounter()
        {
            yield return 0;
            yield return 1;
            yield return 2;
            yield return 3;
        }

        // you can also use "yield break" to stop the Iterator
        // this method would only return half of the values from 0 to limit.
        public static IEnumerable&lt;int&gt; YieldCounterWithBreak(int limit = 10)
        {
            for (var i = 0; i &lt; limit; i++)
            {
                if (i &gt; limit/2) yield break;
                yield return i;
            }
        }

        public static void OtherInterestingFeatures()
        {
            // OPTIONAL PARAMETERS
            MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
            MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones

            // BY REF AND OUT PARAMETERS
            int maxCount = 0, count; // ref params must have value
            MethodSignatures(ref maxCount, out count);

            // EXTENSION METHODS
            int i = 3;
            i.Print(); // Defined below

            // NULLABLE TYPES - great for database interaction / return values
            // any value type (i.e. not a class) can be made nullable by suffixing a ?
            // &lt;type&gt;? &lt;var name&gt; = &lt;value&gt;
            int? nullable = null; // short hand for Nullable&lt;int&gt;
            Console.WriteLine("Nullable variable: " + nullable);
            bool hasValue = nullable.HasValue; // true if not null

            // ?? is syntactic sugar for specifying default value (coalesce)
            // in case variable is null
            int notNullable = nullable ?? 0; // 0

            // ?. is an operator for null-propagation - a shorthand way of checking for null
            nullable?.Print(); // Use the Print() extension method if nullable isn't null

            // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is:
            var magic = "magic is a string, at compile time, so you still get type safety";
            // magic = 9; will not work as magic is a string, not an int

            // GENERICS
            //
            var phonebook = new Dictionary&lt;string, string&gt;() {
                {"Sarah", "212 555 5555"} // Add some entries to the phone book
            };

            // Calling SETDEFAULT defined as a generic above
            Console.WriteLine(SetDefault&lt;string,string&gt;(phonebook, "Shaun", "No Phone")); // No Phone
            // nb, you don't need to specify the TKey and TValue since they can be
            // derived implicitly
            Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555

            // LAMBDA EXPRESSIONS - allow you to write code in line
            Func&lt;int, int&gt; square = (x) =&gt; x * x; // Last T item is the return value
            Console.WriteLine(square(3)); // 9

            // ERROR HANDLING - coping with an uncertain world
            try
            {
                var funBike = PennyFarthing.CreateWithGears(6);

                // will no longer execute because CreateWithGears throws an exception
                string some = "";
                if (true) some = null;
                some.ToLower(); // throws a NullReferenceException
            }
            catch (NotSupportedException)
            {
                Console.WriteLine("Not so much fun now!");
            }
            catch (Exception ex) // catch all other exceptions
            {
                throw new ApplicationException("It hit the fan", ex);
                // throw; // A rethrow that preserves the callstack
            }
            // catch { } // catch-all without capturing the Exception
            finally
            {
                // executes after try or catch
            }

            // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily.
            // Most of objects that access unmanaged resources (file handle, device contexts, etc.)
            // implement the IDisposable interface. The using statement takes care of
            // cleaning those IDisposable objects for you.
            using (StreamWriter writer = new StreamWriter("log.txt"))
            {
                writer.WriteLine("Nothing suspicious here");
                // At the end of scope, resources will be released.
                // Even if an exception is thrown.
            }

            // PARALLEL FRAMEWORK
            // https://devblogs.microsoft.com/csharpfaq/parallel-programming-in-net-framework-4-getting-started/

            var words = new List&lt;string&gt; {"dog", "cat", "horse", "pony"};

            Parallel.ForEach(words,
                new ParallelOptions() { MaxDegreeOfParallelism = 4 },
                word =&gt;
                {
                    Console.WriteLine(word);
                }
            );

            // Running this will produce different outputs
            // since each thread finishes at different times.
            // Some example outputs are:
            // cat dog horse pony
            // dog horse pony cat

            // DYNAMIC OBJECTS (great for working with other languages)
            dynamic student = new ExpandoObject();
            student.FirstName = "First Name"; // No need to define class first!

            // You can even add methods (returns a string, and takes in a string)
            student.Introduce = new Func&lt;string, string&gt;(
                (introduceTo) =&gt; string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
            Console.WriteLine(student.Introduce("Beth"));

            // IQUERYABLE&lt;T&gt; - almost all collections implement this, which gives you a lot of
            // very useful Map / Filter / Reduce style methods
            var bikes = new List&lt;Bicycle&gt;();
            bikes.Sort(); // Sorts the array
            bikes.Sort((b1, b2) =&gt; b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels
            var result = bikes
                .Where(b =&gt; b.Wheels &gt; 3) // Filters - chainable (returns IQueryable of previous type)
                .Where(b =&gt; b.IsBroken &amp;&amp; b.HasTassles)
                .Select(b =&gt; b.ToString()); // Map - we only this selects, so result is a IQueryable&lt;string&gt;

            var sum = bikes.Sum(b =&gt; b.Wheels); // Reduce - sums all the wheels in the collection

            // Create a list of IMPLICIT objects based on some parameters of the bike
            var bikeSummaries = bikes.Select(b=&gt;new { Name = b.Name, IsAwesome = !b.IsBroken &amp;&amp; b.HasTassles });
            // Hard to show here, but you get type ahead completion since the compiler can implicitly work
            // out the types above!
            foreach (var bikeSummary in bikeSummaries.Where(b =&gt; b.IsAwesome))
                Console.WriteLine(bikeSummary.Name);

            // ASPARALLEL
            // And this is where things get wicked - combine linq and parallel operations
            var threeWheelers = bikes.AsParallel().Where(b =&gt; b.Wheels == 3).Select(b =&gt; b.Name);
            // this will happen in parallel! Threads will automagically be spun up and the
            // results divvied amongst them! Amazing for large datasets when you have lots of
            // cores

            // LINQ - maps a store to IQueryable&lt;T&gt; objects, with delayed execution
            // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document
            var db = new BikeRepository();

            // execution is delayed, which is great when querying a database
            var filter = db.Bikes.Where(b =&gt; b.HasTassles); // no query run
            if (42 &gt; 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality
                filter = filter.Where(b =&gt; b.IsBroken); // no query run

            var query = filter
                .OrderBy(b =&gt; b.Wheels)
                .ThenBy(b =&gt; b.Name)
                .Select(b =&gt; b.Name); // still no query run

            // Now the query runs, but opens a reader, so only populates as you iterate through
            foreach (string bike in query)
                Console.WriteLine(result);



        }

    } // End LearnCSharp class

    // You can include other classes in a .cs file

    public static class Extensions
    {
        // EXTENSION METHODS
        public static void Print(this object obj)
        {
            Console.WriteLine(obj.ToString());
        }
    }


    // DELEGATES AND EVENTS
    public class DelegateTest
    {
        public static int count = 0;
        public static int Increment()
        {
            // increment count then return it
            return ++count;
        }

        // A delegate is a reference to a method.
        // To reference the Increment method,
        // first declare a delegate with the same signature,
        // i.e. takes no arguments and returns an int
        public delegate int IncrementDelegate();

        // An event can also be used to trigger delegates
        // Create an event with the delegate type
        public static event IncrementDelegate MyEvent;

        static void Main(string[] args)
        {
            // Refer to the Increment method by instantiating the delegate
            // and passing the method itself in as an argument
            IncrementDelegate inc = new IncrementDelegate(Increment);
            Console.WriteLine(inc());  // =&gt; 1

            // Delegates can be composed with the + operator
            IncrementDelegate composedInc = inc;
            composedInc += inc;
            composedInc += inc;

            // composedInc will run Increment 3 times
            Console.WriteLine(composedInc());  // =&gt; 4


            // Subscribe to the event with the delegate
            MyEvent += new IncrementDelegate(Increment);
            MyEvent += new IncrementDelegate(Increment);

            // Trigger the event
            // ie. run all delegates subscribed to this event
            Console.WriteLine(MyEvent());  // =&gt; 6
        }
    }


    // Class Declaration Syntax:
    // &lt;public/private/protected/internal&gt; class &lt;class name&gt;{
    //    //data fields, constructors, functions all inside.
    //    //functions are called as methods in Java.
    // }

    public class Bicycle
    {
        // Bicycle's Fields/Variables
        public int Cadence // Public: Can be accessed from anywhere
        {
            get // get - define a method to retrieve the property
            {
                return _cadence;
            }
            set // set - define a method to set a property
            {
                _cadence = value; // Value is the value passed in to the setter
            }
        }
        private int _cadence;

        protected virtual int Gear // Protected: Accessible from the class and subclasses
        {
            get; // creates an auto property so you don't need a member field
            set;
        }

        internal int Wheels // Internal: Accessible from within the assembly
        {
            get;
            private set; // You can set modifiers on the get/set methods
        }

        int _speed; // Everything is private by default: Only accessible from within this class.
                    // can also use keyword private
        public string Name { get; set; }

        // Properties also have a special syntax for when you want a readonly property
        // that simply returns the result of an expression
        public string LongName =&gt; Name + " " + _speed + " speed";

        // Enum is a value type that consists of a set of named constants
        // It is really just mapping a name to a value (an int, unless specified otherwise).
        // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
        // An enum can't contain the same value twice.
        public enum BikeBrand
        {
            AIST,
            BMC,
            Electra = 42, //you can explicitly set a value to a name
            Gitane // 43
        }
        // We defined this type inside a Bicycle class, so it is a nested type
        // Code outside of this class should reference this type as Bicycle.BikeBrand

        public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type

        // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on
        // Any class derived from Attribute can be used to decorate types, methods, parameters etc
        // Bitwise operators &amp; and | can be used to perform and/or operations

        [Flags]
        public enum BikeAccessories
        {
            None = 0,
            Bell = 1,
            MudGuards = 2, // need to set the values manually!
            Racks = 4,
            Lights = 8,
            FullPackage = Bell | MudGuards | Racks | Lights
        }

        // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell)
        // Before .NET 4: (aBike.Accessories &amp; Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell
        public BikeAccessories Accessories { get; set; }

        // Static members belong to the type itself rather than specific object.
        // You can access them without a reference to any object:
        // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated);
        public static int BicyclesCreated { get; set; }

        // readonly values are set at run time
        // they can only be assigned upon declaration or in a constructor
        readonly bool _hasCardsInSpokes = false; // read-only private

        // Constructors are a way of creating classes
        // This is a default constructor
        public Bicycle()
        {
            this.Gear = 1; // you can access members of the object with the keyword this
            Cadence = 50;  // but you don't always need it
            _speed = 5;
            Name = "Bontrager";
            Brand = BikeBrand.AIST;
            BicyclesCreated++;
        }

        // This is a specified constructor (it contains arguments)
        public Bicycle(int startCadence, int startSpeed, int startGear,
                       string name, bool hasCardsInSpokes, BikeBrand brand)
            : base() // calls base first
        {
            Gear = startGear;
            Cadence = startCadence;
            _speed = startSpeed;
            Name = name;
            _hasCardsInSpokes = hasCardsInSpokes;
            Brand = brand;
        }

        // Constructors can be chained
        public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
            this(startCadence, startSpeed, 0, "big wheels", true, brand)
        {
        }

        // Function Syntax:
        // &lt;public/private/protected&gt; &lt;return type&gt; &lt;function name&gt;(&lt;args&gt;)

        // classes can implement getters and setters for their fields
        // or they can implement properties (this is the preferred way in C#)

        // Method parameters can have default values.
        // In this case, methods can be called with these parameters omitted
        public void SpeedUp(int increment = 1)
        {
            _speed += increment;
        }

        public void SlowDown(int decrement = 1)
        {
            _speed -= decrement;
        }

        // properties get/set values
        // when only data needs to be accessed, consider using properties.
        // properties may have either get or set, or both
        private bool _hasTassles; // private variable
        public bool HasTassles // public accessor
        {
            get { return _hasTassles; }
            set { _hasTassles = value; }
        }

        // You can also define an automatic property in one line
        // this syntax will create a backing field automatically.
        // You can set an access modifier on either the getter or the setter (or both)
        // to restrict its access:
        public bool IsBroken { get; private set; }

        // Properties can be auto-implemented
        public int FrameSize
        {
            get;
            // you are able to specify access modifiers for either get or set
            // this means only Bicycle class can call set on Framesize
            private set;
        }

        // It's also possible to define custom Indexers on objects.
        // Although this is not entirely useful in this example, you
        // could do bicycle[0] which returns "chris" to get the first passenger or
        // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle)
        private string[] passengers = { "chris", "phil", "darren", "regina" };

        public string this[int i]
        {
            get {
                return passengers[i];
            }

            set {
                passengers[i] = value;
            }
        }

        // Method to display the attribute values of this Object.
        public virtual string Info()
        {
            return "Gear: " + Gear +
                    " Cadence: " + Cadence +
                    " Speed: " + _speed +
                    " Name: " + Name +
                    " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") +
                    "\n------------------------------\n"
                    ;
        }

        // Methods can also be static. It can be useful for helper methods
        public static bool DidWeCreateEnoughBicycles()
        {
            // Within a static method, we only can reference static class members
            return BicyclesCreated &gt; 9000;
        } // If your class only needs static members, consider marking the class itself as static.


    } // end class Bicycle

    // PennyFarthing is a subclass of Bicycle
    class PennyFarthing : Bicycle
    {
        // (Penny Farthings are those bicycles with the big front wheel.
        // They have no gears.)

        // calling parent constructor
        public PennyFarthing(int startCadence, int startSpeed) :
            base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra)
        {
        }

        protected override int Gear
        {
            get
            {
                return 0;
            }
            set
            {
                throw new InvalidOperationException("You can't change gears on a PennyFarthing");
            }
        }

        public static PennyFarthing CreateWithGears(int gears)
        {
            var penny = new PennyFarthing(1, 1);
            penny.Gear = gears; // Oops, can't do this!
            return penny;
        }

        public override string Info()
        {
            string result = "PennyFarthing bicycle ";
            result += base.ToString(); // Calling the base version of the method
            return result;
        }
    }

    // Interfaces only contain signatures of the members, without the implementation.
    interface IJumpable
    {
        void Jump(int meters); // all interface members are implicitly public
    }

    interface IBreakable
    {
        bool Broken { get; } // interfaces can contain properties as well as methods &amp; events
    }

    // Classes can inherit only one other class, but can implement any amount of interfaces,
    // however the base class name must be the first in the list and all interfaces follow
    class MountainBike : Bicycle, IJumpable, IBreakable
    {
        int damage = 0;

        public void Jump(int meters)
        {
            damage += meters;
        }

        public bool Broken
        {
            get
            {
                return damage &gt; 100;
            }
        }
    }

    /// &lt;summary&gt;
    /// Used to connect to DB for LinqToSql example.
    /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
    /// https://docs.microsoft.com/ef/ef6/modeling/code-first/workflows/new-database
    /// &lt;/summary&gt;
    public class BikeRepository : DbContext
    {
        public BikeRepository()
            : base()
        {
        }

        public DbSet&lt;Bicycle&gt; Bikes { get; set; }
    }

    // Classes can be split across multiple .cs files
    // A1.cs
    public partial class A
    {
        public static void A1()
        {
            Console.WriteLine("Method A1 in class A");
        }
    }

    // A2.cs
    public partial class A
    {
        public static void A2()
        {
            Console.WriteLine("Method A2 in class A");
        }
    }

    // Program using the partial class "A"
    public class Program
    {
        static void Main()
        {
            A.A1();
            A.A2();
        }
    }

    // String interpolation by prefixing the string with $
    // and wrapping the expression you want to interpolate with { braces }
    // You can also combine both interpolated and verbatim strings with $@
    public class Rectangle
    {
        public int Length { get; set; }
        public int Width { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Rectangle rect = new Rectangle { Length = 5, Width = 3 };
            Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}");

            string username = "User";
            Console.WriteLine($@"C:\Users\{username}\Desktop");
        }
    }

    // New C# 6 features
    class GlassBall : IJumpable, IBreakable
    {
        // Autoproperty initializers
        public int Damage { get; private set; } = 0;

        // Autoproperty initializers on getter-only properties
        public string Name { get; } = "Glass ball";

        // Getter-only autoproperty that is initialized in constructor
        public string GenieName { get; }

        public GlassBall(string genieName = null)
        {
            GenieName = genieName;
        }

        public void Jump(int meters)
        {
            if (meters &lt; 0)
                // New nameof() expression; compiler will check that the identifier exists
                // nameof(x) == "x"
                // Prevents e.g. parameter names changing but not updated in error messages
                throw new ArgumentException("Cannot jump negative amount!", nameof(meters));

            Damage += meters;
        }

        // Expression-bodied properties ...
        public bool Broken
            =&gt; Damage &gt; 100;

        // ... and methods
        public override string ToString()
            // Interpolated string
            =&gt; $"{Name}. Damage taken: {Damage}";

        public string SummonGenie()
            // Null-conditional operators
            // x?.y will return null immediately if x is null; y is not evaluated
            =&gt; GenieName?.ToUpper();
    }

    static class MagicService
    {
        private static bool LogException(Exception ex)
        {
            // log exception somewhere
            return false;
        }

        public static bool CastSpell(string spell)
        {
            try
            {
                // Pretend we call API here
                throw new MagicServiceException("Spell failed", 42);

                // Spell succeeded
                return true;
            }
            // Only catch if Code is 42 i.e. spell failed
            catch(MagicServiceException ex) when (ex.Code == 42)
            {
                // Spell failed
                return false;
            }
            // Other exceptions, or MagicServiceException where Code is not 42
            catch(Exception ex) when (LogException(ex))
            {
                // Execution never reaches this block
                // The stack is not unwound
            }
            return false;
            // Note that catching a MagicServiceException and rethrowing if Code
            // is not 42 or 117 is different, as then the final catch-all block
            // will not catch the rethrown exception
        }
    }

    public class MagicServiceException : Exception
    {
        public int Code { get; }

        public MagicServiceException(string message, int code) : base(message)
        {
            Code = code;
        }
    }

    public static class PragmaWarning {
        // Obsolete attribute
        [Obsolete("Use NewMethod instead", false)]
        public static void ObsoleteMethod()
        {
            // obsolete code
        }

        public static void NewMethod()
        {
            // new code
        }

        public static void Main()
        {
            ObsoleteMethod(); // CS0618: 'ObsoleteMethod is obsolete: Use NewMethod instead'
#pragma warning disable CS0618
            ObsoleteMethod(); // no warning
#pragma warning restore CS0618
            ObsoleteMethod(); // CS0618: 'ObsoleteMethod is obsolete: Use NewMethod instead'
        }
    }
} // End Namespace

using System;
// C# 6, static using
using static System.Math;

namespace Learning.More.CSharp
{
    class StaticUsing
    {
        static void Main()
        {
            // Without a static using statement..
            Console.WriteLine("The square root of 4 is {}.", Math.Sqrt(4));
            // With one
            Console.WriteLine("The square root of 4 is {}.", Sqrt(4));
        }
    }
}

// New C# 7 Feature
// Install Microsoft.Net.Compilers Latest from Nuget
// Install System.ValueTuple Latest from Nuget
using System;
namespace Csharp7
{
    // TUPLES, DECONSTRUCTION AND DISCARDS
    class TuplesTest
    {
        public (string, string) GetName()
        {
            // Fields in tuples are by default named Item1, Item2...
            var names1 = ("Peter", "Parker");
            Console.WriteLine(names1.Item2);  // =&gt; Parker

            // Fields can instead be explicitly named
            // Type 1 Declaration
            (string FirstName, string LastName) names2 = ("Peter", "Parker");

            // Type 2 Declaration
            var names3 = (First:"Peter", Last:"Parker");

            Console.WriteLine(names2.FirstName);  // =&gt; Peter
            Console.WriteLine(names3.Last);  // =&gt; Parker

            return names3;
        }

        public string GetLastName() {
            var fullName = GetName();

            // Tuples can be deconstructed
            (string firstName, string lastName) = fullName;

            // Fields in a deconstructed tuple can be discarded by using _
            var (_, last) = fullName;
            return last;
        }

        // Any type can be deconstructed in the same way by
        // specifying a Deconstruct method
        public int randomNumber = 4;
        public int anotherRandomNumber = 10;

        public void Deconstruct(out int randomNumber, out int anotherRandomNumber)
        {
            randomNumber = this.randomNumber;
            anotherRandomNumber = this.anotherRandomNumber;
        }

        static void Main(string[] args)
        {
            var tt = new TuplesTest();
            (int num1, int num2) = tt;
            Console.WriteLine($"num1: {num1}, num2: {num2}");  // =&gt; num1: 4, num2: 10

            Console.WriteLine(tt.GetLastName());
        }
    }

    // PATTERN MATCHING
    class PatternMatchingTest
    {
        public static (string, int)? CreateLogMessage(object data)
        {
            switch(data)
            {
                // Additional filtering using when
                case System.Net.Http.HttpRequestException h when h.Message.Contains("404"):
                    return (h.Message, 404);
                case System.Net.Http.HttpRequestException h when h.Message.Contains("400"):
                    return (h.Message, 400);
                case Exception e:
                    return (e.Message, 500);
                case string s:
                    return (s, s.Contains("Error") ? 500 : 200);
                case null:
                    return null;
                default:
                    return (data.ToString(), 500);
            }
        }
    }

    // REFERENCE LOCALS
    // Allow you to return a reference to an object instead of just its value
    class RefLocalsTest
    {
        // note ref in return
        public static ref string FindItem(string[] arr, string el)
        {
            for(int i=0; i&lt;arr.Length; i++)
            {
                if(arr[i] == el) {
                    // return the reference
                    return ref arr[i];
                }
            }
            throw new Exception("Item not found");
        }

        public static void SomeMethod()
        {
            string[] arr = {"this", "is", "an", "array"};

            // note refs everywhere
            ref string item = ref FindItem(arr, "array");
            item = "apple";
            Console.WriteLine(arr[3]);  // =&gt; apple
        }
    }

    // LOCAL FUNCTIONS
    class LocalFunctionTest
    {
        private static int _id = 0;
        public int id;
        public LocalFunctionTest()
        {
            id = generateId();

            // This local function can only be accessed in this scope
            int generateId()
            {
                return _id++;
            }
        }

        public static void AnotherMethod()
        {
            var lf1 = new LocalFunctionTest();
            var lf2 = new LocalFunctionTest();
            Console.WriteLine($"{lf1.id}, {lf2.id}");  // =&gt; 0, 1

            int id = generateId();
            // error CS0103: The name 'generateId' does not exist in the current context
        }
    }
}
</code></pre>
<p>C++:</p>
<pre><code class="lang-plaintext">//////////////////
// Comparison to C
//////////////////

// C++ is almost a superset of C and shares its basic syntax for
// variable declarations, primitive types, and functions.

// Just like in C, your program's entry point is a function called
// main with an integer return type.
// This value serves as the program's exit status.
// See https://en.wikipedia.org/wiki/Exit_status for more information.
int main(int argc, char** argv)
{
    // Command line arguments are passed in by argc and argv in the same way
    // they are in C.
    // argc indicates the number of arguments,
    // and argv is an array of C-style strings (char*)
    // representing the arguments.
    // The first argument is the name by which the program was called.
    // argc and argv can be omitted if you do not care about arguments,
    // giving the function signature of int main()

    // An exit status of 0 indicates success.
    return 0;
}

// However, C++ varies in some of the following ways:

// In C++, character literals are chars, therefore the size is 1
sizeof('c') == sizeof(char)

// In C, character literals are ints, therefore the size is 4
sizeof('c') == sizeof(int)


// C++ has strict prototyping
void func(); // function which accepts no arguments
void func(void); // same as earlier

// In C
void func(); // function which may accept any number of arguments with unknown type
void func(void); // function which accepts no arguments

// Use nullptr instead of NULL in C++
int* ip = nullptr;

// Most C standard headers are available in C++.
// C headers generally end with .h, while
// C++ headers are prefixed with "c" and have no ".h" suffix.

// The C++ standard version:
#include &lt;cstdio&gt;

// The C standard version:
#include &lt;stdio.h&gt;

int main()
{
    printf("Hello, world!\n");
    return 0;
}

///////////////////////
// Function overloading
///////////////////////

// C++ supports function overloading
// provided each function takes different parameters.

void print(char const* myString)
{
    printf("String %s\n", myString);
}

void print(int myInt)
{
    printf("My int is %d\n", myInt);
}

int main()
{
    print("Hello"); // Resolves to void print(const char*)
    print(15); // Resolves to void print(int)
}

/////////////////////////////
// Default function arguments
/////////////////////////////

// You can provide default arguments for a function
// if they are not provided by the caller.

void doSomethingWithInts(int a = 1, int b = 4)
{
    // Do something with the ints here
}

int main()
{
    doSomethingWithInts();      // a = 1,  b = 4
    doSomethingWithInts(20);    // a = 20, b = 4
    doSomethingWithInts(20, 5); // a = 20, b = 5
}

// Default arguments must be at the end of the arguments list.

void invalidDeclaration(int a = 1, int b) // Error!
{
}


/////////////
// Namespaces
/////////////

// Namespaces provide separate scopes for variable, function,
// and other declarations.
// Namespaces can be nested.

namespace First {
    namespace Nested {
        void foo()
        {
            printf("This is First::Nested::foo\n");
        }
    } // end namespace Nested
} // end namespace First

namespace Second {
    void foo()
    {
        printf("This is Second::foo\n");
    }
    void bar()
    {
        printf("This is Second::bar\n");
    }
}

void foo()
{
    printf("This is global foo\n");
}

int main()
{
    // Includes all symbols from namespace Second into the current scope. Note
    // that while bar() works, simply using foo() no longer works, since it is
    // now ambiguous whether we're calling the foo in namespace Second or the
    // top level.
    using namespace Second;

    bar(); // prints "This is Second::bar"
    Second::foo(); // prints "This is Second::foo"
    First::Nested::foo(); // prints "This is First::Nested::foo"
    ::foo(); // prints "This is global foo"
}

///////////////
// Input/Output
///////////////

// C++ input and output uses streams
// cin, cout, and cerr represent stdin, stdout, and stderr.
// &lt;&lt; is the insertion operator and &gt;&gt; is the extraction operator.

#include &lt;iostream&gt; // Include for I/O streams

int main()
{
    int myInt;

    // Prints to stdout (or terminal/screen)
    // std::cout referring the access to the std namespace
    std::cout &lt;&lt; "Enter your favorite number:\n";
    // Takes in input
    std::cin &gt;&gt; myInt;

    // cout can also be formatted
    std::cout &lt;&lt; "Your favorite number is " &lt;&lt; myInt &lt;&lt; '\n';
    // prints "Your favorite number is &lt;myInt&gt;"

    std::cerr &lt;&lt; "Used for error messages";

    // flush string stream buffer with new line
    std::cout &lt;&lt; "I flushed it away" &lt;&lt; std::endl;
}

//////////
// Strings
//////////

// Strings in C++ are objects and have many member functions
#include &lt;string&gt;

std::string myString = "Hello";
std::string myOtherString = " World";

// + is used for concatenation.
std::cout &lt;&lt; myString + myOtherString; // "Hello World"

std::cout &lt;&lt; myString + " You"; // "Hello You"

// C++ string length can be found from either string::length() or string::size()
cout &lt;&lt; myString.length() + myOtherString.size(); // Outputs 11 (= 5 + 6).

// C++ strings are mutable.
myString.append(" Dog");
std::cout &lt;&lt; myString; // "Hello Dog"

// C++ can handle C-style strings with related functions using cstrings
#include &lt;cstring&gt;

char myOldString[10] = "Hello CPP";
cout &lt;&lt; myOldString;
cout &lt;&lt; "Length = " &lt;&lt; strlen(myOldString); // Length = 9

/////////////
// References
/////////////

// In addition to pointers like the ones in C,
// C++ has _references_.
// These are pointer types that cannot be reassigned once set
// and cannot be null.
// They also have the same syntax as the variable itself:
// No * is needed for dereferencing and
// &amp; (address of) is not used for assignment.

std::string foo = "I am foo";
std::string bar = "I am bar";

std::string&amp; fooRef = foo; // This creates a reference to foo.
fooRef += ". Hi!"; // Modifies foo through the reference
std::cout &lt;&lt; fooRef; // Prints "I am foo. Hi!"

std::cout &lt;&lt; &amp;fooRef &lt;&lt; '\n'; // Prints the address of foo
// Doesn't reassign "fooRef". This is the same as "foo = bar", and
//   foo == "I am bar"
// after this line.
fooRef = bar;
std::cout &lt;&lt; &amp;fooRef &lt;&lt; '\n'; // Still prints the address of foo
std::cout &lt;&lt; fooRef &lt;&lt; '\n';  // Prints "I am bar"

// The address of fooRef remains the same, i.e. it is still referring to foo.


const std::string&amp; barRef = bar; // Create a const reference to bar.
// Like C, const values (and pointers and references) cannot be modified.
barRef += ". Hi!"; // Error, const references cannot be modified.

// Sidetrack: Before we talk more about references, we must introduce a concept
// called a temporary object. Suppose we have the following code:
std::string tempObjectFun() { ... }
std::string retVal = tempObjectFun();

// What happens in the second line is actually:
//   - a string object is returned from tempObjectFun
//   - a new string is constructed with the returned object as argument to the
//     constructor
//   - the returned object is destroyed
// The returned object is called a temporary object. Temporary objects are
// created whenever a function returns an object, and they are destroyed at the
// end of the evaluation of the enclosing expression (Well, this is what the
// standard says, but compilers are allowed to change this behavior. Look up
// "return value optimization" if you're into these kinds of details). So in
// this code:
foo(bar(tempObjectFun()))

// assuming foo and bar exist, the object returned from tempObjectFun is
// passed to bar, and it is destroyed before foo is called.

// Now back to references. The exception to the "at the end of the enclosing
// expression" rule is if a temporary object is bound to a const reference, in
// which case its life gets extended to the current scope:

void constReferenceTempObjectFun() {
    // constRef gets the temporary object, and it is valid until the end of this
    // function.
    const std::string&amp; constRef = tempObjectFun();
    ...
}

// Another kind of reference introduced in C++11 is specifically for temporary
// objects. You cannot have a variable of its type, but it takes precedence in
// overload resolution:

void someFun(std::string&amp; s) { ... }  // Regular reference
void someFun(std::string&amp;&amp; s) { ... }  // Reference to temporary object

std::string foo;
someFun(foo);  // Calls the version with regular reference
someFun(tempObjectFun());  // Calls the version with temporary reference

// For example, you will see these two versions of constructors for
// std::basic_string:
std::basic_string(const basic_string&amp; other);
std::basic_string(basic_string&amp;&amp; other);

// Idea being if we are constructing a new string from a temporary object (which
// is going to be destroyed soon anyway), we can have a more efficient
// constructor that "salvages" parts of that temporary string. You will see this
// concept referred to as "move semantics".

/////////////////////
// Enums
/////////////////////

// Enums are a way to assign a value to a constant most commonly used for
// easier visualization and reading of code
enum ECarTypes
{
    Sedan,
    Hatchback,
    SUV,
    Wagon
};

ECarTypes GetPreferredCarType()
{
    return ECarTypes::Hatchback;
}

// As of C++11 there is an easy way to assign a type to the enum which can be
// useful in serialization of data and converting enums back-and-forth between
// the desired type and their respective constants
enum ECarTypes : uint8_t
{
    Sedan, // 0
    Hatchback, // 1
    SUV = 254, // 254
    Hybrid // 255
};

void WriteByteToFile(uint8_t InputValue)
{
    // Serialize the InputValue to a file
}

void WritePreferredCarTypeToFile(ECarTypes InputCarType)
{
    // The enum is implicitly converted to a uint8_t due to its declared enum type
    WriteByteToFile(InputCarType);
}

// On the other hand you may not want enums to be accidentally cast to an integer
// type or to other enums so it is instead possible to create an enum class which
// won't be implicitly converted
enum class ECarTypes : uint8_t
{
    Sedan, // 0
    Hatchback, // 1
    SUV = 254, // 254
    Hybrid // 255
};

void WriteByteToFile(uint8_t InputValue)
{
    // Serialize the InputValue to a file
}

void WritePreferredCarTypeToFile(ECarTypes InputCarType)
{
    // Won't compile even though ECarTypes is a uint8_t due to the enum
    // being declared as an "enum class"!
    WriteByteToFile(InputCarType);
}

//////////////////////////////////////////
// Classes and object-oriented programming
//////////////////////////////////////////

// First example of classes
#include &lt;iostream&gt;

// Declare a class.
// Classes are usually declared in header (.h or .hpp) files.
class Dog {
    // Member variables and functions are private by default.
    std::string name;
    int weight;

// All members following this are public
// until "private:" or "protected:" is found.
public:

    // Default constructor
    Dog();

    // Member function declarations (implementations to follow)
    // Note that we use std::string here instead of placing
    // using namespace std;
    // above.
    // Never put a "using namespace" statement in a header.
    void setName(const std::string&amp; dogsName);

    void setWeight(int dogsWeight);

    // Functions that do not modify the state of the object
    // should be marked as const.
    // This allows you to call them if given a const reference to the object.
    // Also note the functions must be explicitly declared as _virtual_
    // in order to be overridden in derived classes.
    // Functions are not virtual by default for performance reasons.
    virtual void print() const;

    // Functions can also be defined inside the class body.
    // Functions defined as such are automatically inlined.
    void bark() const { std::cout &lt;&lt; name &lt;&lt; " barks!\n"; }

    // Along with constructors, C++ provides destructors.
    // These are called when an object is deleted or falls out of scope.
    // This enables powerful paradigms such as RAII
    // (see below)
    // The destructor should be virtual if a class is to be derived from;
    // if it is not virtual, then the derived class' destructor will
    // not be called if the object is destroyed through a base-class reference
    // or pointer.
    virtual ~Dog();

}; // A semicolon must follow the class definition.

// Class member functions are usually implemented in .cpp files.
Dog::Dog()
{
    std::cout &lt;&lt; "A dog has been constructed\n";
}

// Objects (such as strings) should be passed by reference
// if you are modifying them or const reference if you are not.
void Dog::setName(const std::string&amp; dogsName)
{
    name = dogsName;
}

void Dog::setWeight(int dogsWeight)
{
    weight = dogsWeight;
}

// Notice that "virtual" is only needed in the declaration, not the definition.
void Dog::print() const
{
    std::cout &lt;&lt; "Dog is " &lt;&lt; name &lt;&lt; " and weighs " &lt;&lt; weight &lt;&lt; "kg\n";
}

Dog::~Dog()
{
    std::cout &lt;&lt; "Goodbye " &lt;&lt; name &lt;&lt; '\n';
}

int main() {
    Dog myDog; // prints "A dog has been constructed"
    myDog.setName("Barkley");
    myDog.setWeight(10);
    myDog.print(); // prints "Dog is Barkley and weighs 10 kg"
    return 0;
} // prints "Goodbye Barkley"

// Inheritance:

// This class inherits everything public and protected from the Dog class
// as well as private but may not directly access private members/methods
// without a public or protected method for doing so
class OwnedDog : public Dog {

public:
    void setOwner(const std::string&amp; dogsOwner);

    // Override the behavior of the print function for all OwnedDogs. See
    // https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
    // for a more general introduction if you are unfamiliar with
    // subtype polymorphism.
    // The override keyword is optional but makes sure you are actually
    // overriding the method in a base class.
    void print() const override;

private:
    std::string owner;
};

// Meanwhile, in the corresponding .cpp file:

void OwnedDog::setOwner(const std::string&amp; dogsOwner)
{
    owner = dogsOwner;
}

void OwnedDog::print() const
{
    Dog::print(); // Call the print function in the base Dog class
    std::cout &lt;&lt; "Dog is owned by " &lt;&lt; owner &lt;&lt; '\n';
    // Prints "Dog is &lt;name&gt; and weights &lt;weight&gt;"
    //        "Dog is owned by &lt;owner&gt;"
}

//////////////////////////////////////////
// Initialization and Operator Overloading
//////////////////////////////////////////

// In C++ you can overload the behavior of operators such as +, -, *, /, etc.
// This is done by defining a function which is called
// whenever the operator is used.

#include &lt;iostream&gt;
using namespace std;

class Point {
public:
    // Member variables can be given default values in this manner.
    double x = 0;
    double y = 0;

    // Define a default constructor which does nothing
    // but initialize the Point to the default value (0, 0)
    Point() { };

    // The following syntax is known as an initialization list
    // and is the proper way to initialize class member values
    Point (double a, double b) :
        x(a),
        y(b)
    { /* Do nothing except initialize the values */ }

    // Overload the + operator.
    Point operator+(const Point&amp; rhs) const;

    // Overload the += operator
    Point&amp; operator+=(const Point&amp; rhs);

    // It would also make sense to add the - and -= operators,
    // but we will skip those for brevity.
};

Point Point::operator+(const Point&amp; rhs) const
{
    // Create a new point that is the sum of this one and rhs.
    return Point(x + rhs.x, y + rhs.y);
}

// It's good practice to return a reference to the leftmost variable of
// an assignment. `(a += b) == c` will work this way.
Point&amp; Point::operator+=(const Point&amp; rhs)
{
    x += rhs.x;
    y += rhs.y;

    // `this` is a pointer to the object, on which a method is called.
    return *this;
}

int main () {
    Point up (0,1);
    Point right (1,0);
    // This calls the Point + operator
    // Point up calls the + (function) with right as its parameter
    Point result = up + right;
    // Prints "Result is upright (1,1)"
    std::cout &lt;&lt; "Result is upright (" &lt;&lt; result.x &lt;&lt; ',' &lt;&lt; result.y &lt;&lt; ")\n";
    return 0;
}

/////////////////////
// Templates
/////////////////////

// Templates in C++ are mostly used for generic programming, though they are
// much more powerful than generic constructs in other languages. They also
// support explicit and partial specialization and functional-style type
// classes; in fact, they are a Turing-complete functional language embedded
// in C++!

// We start with the kind of generic programming you might be familiar with. To
// define a class or function that takes a type parameter:
template&lt;class T&gt;
class Box {
public:
    // In this class, T can be used as any other type.
    void insert(const T&amp;) { ... }
};

// During compilation, the compiler actually generates copies of each template
// with parameters substituted, so the full definition of the class must be
// present at each invocation. This is why you will see template classes defined
// entirely in header files.

// To instantiate a template class on the stack:
Box&lt;int&gt; intBox;

// and you can use it as you would expect:
intBox.insert(123);

// You can, of course, nest templates:
Box&lt;Box&lt;int&gt; &gt; boxOfBox;
boxOfBox.insert(intBox);

// Until C++11, you had to place a space between the two '&gt;'s, otherwise '&gt;&gt;'
// would be parsed as the right shift operator.

// You will sometimes see
//   template&lt;typename T&gt;
// instead. The 'class' keyword and 'typename' keywords are _mostly_
// interchangeable in this case. For the full explanation, see
//   https://en.wikipedia.org/wiki/Typename
// (yes, that keyword has its own Wikipedia page).

// Similarly, a template function:
template&lt;class T&gt;
void barkThreeTimes(const T&amp; input)
{
    input.bark();
    input.bark();
    input.bark();
}

// Notice that nothing is specified about the type parameters here. The compiler
// will generate and then type-check every invocation of the template, so the
// above function works with any type 'T' that has a const 'bark' method!

Dog fluffy;
fluffy.setName("Fluffy")
barkThreeTimes(fluffy); // Prints "Fluffy barks" three times.

// Template parameters don't have to be classes:
template&lt;int Y&gt;
void printMessage() {
    std::cout &lt;&lt; "Learn C++ in " &lt;&lt; Y &lt;&lt; " minutes!\n";
}

// And you can explicitly specialize templates for more efficient code. Of
// course, most real-world uses of specialization are not as trivial as this.
// Note that you still need to declare the function (or class) as a template
// even if you explicitly specified all parameters.
template&lt;&gt;
void printMessage&lt;10&gt;() {
    std::cout &lt;&lt; "Learn C++ faster in only 10 minutes!\n";
}

printMessage&lt;20&gt;();  // Prints "Learn C++ in 20 minutes!"
printMessage&lt;10&gt;();  // Prints "Learn C++ faster in only 10 minutes!"


/////////////////////
// Exception Handling
/////////////////////

// The standard library provides a few exception types
// (see https://en.cppreference.com/w/cpp/error/exception)
// but any type can be thrown as an exception
#include &lt;exception&gt;
#include &lt;stdexcept&gt;

// All exceptions thrown inside the _try_ block can be caught by subsequent
// _catch_ handlers.
try {
    // Do not allocate exceptions on the heap using _new_.
    throw std::runtime_error("A problem occurred");
}

// Catch exceptions by const reference if they are objects
catch (const std::exception&amp; ex)
{
    std::cout &lt;&lt; ex.what();
}

// Catches any exception not caught by previous _catch_ blocks
catch (...)
{
    std::cout &lt;&lt; "Unknown exception caught";
    throw; // Re-throws the exception
}

///////
// RAII
///////

// RAII stands for "Resource Acquisition Is Initialization".
// It is often considered the most powerful paradigm in C++
// and is the simple concept that a constructor for an object
// acquires that object's resources and the destructor releases them.

// To understand how this is useful,
// consider a function that uses a C file handle:
void doSomethingWithAFile(const char* filename)
{
    // To begin with, assume nothing can fail.

    FILE* fh = fopen(filename, "r"); // Open the file in read mode.
    if (fh == NULL) {
        // Handle possible error
    }

    doSomethingWithTheFile(fh);
    doSomethingElseWithIt(fh);

    fclose(fh); // Close the file handle.
}

// Unfortunately, things are quickly complicated by error handling.
// Suppose fopen can fail, and that doSomethingWithTheFile and
// doSomethingElseWithIt return error codes if they fail.
//  (Exceptions are the preferred way of handling failure,
//   but some programmers, especially those with a C background,
//   disagree on the utility of exceptions).
// We now have to check each call for failure and close the file handle
// if a problem occurred.
bool doSomethingWithAFile(const char* filename)
{
    FILE* fh = fopen(filename, "r"); // Open the file in read mode
    if (fh == nullptr) // The returned pointer is null on failure.
        return false; // Report that failure to the caller.

    // Assume each function returns false if it failed
    if (!doSomethingWithTheFile(fh)) {
        fclose(fh); // Close the file handle so it doesn't leak.
        return false; // Propagate the error.
    }
    if (!doSomethingElseWithIt(fh)) {
        fclose(fh); // Close the file handle so it doesn't leak.
        return false; // Propagate the error.
    }

    fclose(fh); // Close the file handle so it doesn't leak.
    return true; // Indicate success
}

// C programmers often clean this up a little bit using goto:
bool doSomethingWithAFile(const char* filename)
{
    FILE* fh = fopen(filename, "r");
    if (fh == nullptr)
        return false;

    if (!doSomethingWithTheFile(fh))
        goto failure;

    if (!doSomethingElseWithIt(fh))
        goto failure;

    fclose(fh); // Close the file
    return true; // Indicate success

failure:
    fclose(fh);
    return false; // Propagate the error
}

// If the functions indicate errors using exceptions,
// things are a little cleaner, but still sub-optimal.
void doSomethingWithAFile(const char* filename)
{
    FILE* fh = fopen(filename, "r"); // Open the file in shared_ptrread mode
    if (fh == nullptr)
        throw std::runtime_error("Could not open the file.");

    try {
        doSomethingWithTheFile(fh);
        doSomethingElseWithIt(fh);
    }
    catch (...) {
        fclose(fh); // Be sure to close the file if an error occurs.
        throw; // Then re-throw the exception.
    }

    fclose(fh); // Close the file
    // Everything succeeded
}

// Compare this to the use of C++'s file stream class (fstream)
// fstream uses its destructor to close the file.
// Recall from above that destructors are automatically called
// whenever an object falls out of scope.
void doSomethingWithAFile(const std::string&amp; filename)
{
    // ifstream is short for input file stream
    std::ifstream fh(filename); // Open the file

    // Do things with the file
    doSomethingWithTheFile(fh);
    doSomethingElseWithIt(fh);

} // The file is automatically closed here by the destructor

// This has _massive_ advantages:
// 1. No matter what happens,
//    the resource (in this case the file handle) will be cleaned up.
//    Once you write the destructor correctly,
//    It is _impossible_ to forget to close the handle and leak the resource.
// 2. Note that the code is much cleaner.
//    The destructor handles closing the file behind the scenes
//    without you having to worry about it.
// 3. The code is exception safe.
//    An exception can be thrown anywhere in the function and cleanup
//    will still occur.

// All idiomatic C++ code uses RAII extensively for all resources.
// Additional examples include
// - Memory using unique_ptr and shared_ptr
// - Containers - the standard library linked list,
//   vector (i.e. self-resizing array), hash maps, and so on
//   all automatically destroy their contents when they fall out of scope.
// - Mutexes using lock_guard and unique_lock


/////////////////////
// Smart Pointer
/////////////////////

// Generally a smart pointer is a class which wraps a "raw pointer" (usage of "new"
// respectively malloc/calloc in C). The goal is to be able to
// manage the lifetime of the object being pointed to without ever needing to explicitly delete
// the object. The term itself simply describes a set of pointers with the
// mentioned abstraction.
// Smart pointers should be preferred over raw pointers, to prevent
// risky memory leaks, which happen if you forget to delete an object.

// Usage of a raw pointer:
Dog* ptr = new Dog();
ptr-&gt;bark();
delete ptr;

// By using a smart pointer, you don't have to worry about the deletion
// of the object anymore.
// A smart pointer describes a policy, to count the references to the
// pointer. The object gets destroyed when the last
// reference to the object gets destroyed.

// Usage of "std::shared_ptr":
void foo()
{
    // It's no longer necessary to delete the Dog.
    std::shared_ptr&lt;Dog&gt; doggo(new Dog());
    doggo-&gt;bark();
}

// Beware of possible circular references!!!
// There will be always a reference, so it will be never destroyed!
std::shared_ptr&lt;Dog&gt; doggo_one(new Dog());
std::shared_ptr&lt;Dog&gt; doggo_two(new Dog());
doggo_one = doggo_two; // p1 references p2
doggo_two = doggo_one; // p2 references p1

// There are several kinds of smart pointers.
// The way you have to use them is always the same.
// This leads us to the question: when should we use each kind of smart pointer?
// std::unique_ptr - use it when you just want to hold one reference to
// the object.
// std::shared_ptr - use it when you want to hold multiple references to the
// same object and want to make sure that it's deallocated
// when all references are gone.
// std::weak_ptr - use it when you want to access
// the underlying object of a std::shared_ptr without causing that object to stay allocated.
// Weak pointers are used to prevent circular referencing.


/////////////////////
// Containers
/////////////////////

// Containers or the Standard Template Library are some predefined templates.
// They manage the storage space for its elements and provide
// member functions to access and manipulate them.

// Few containers are as follows:

// Vector (Dynamic array)
// Allow us to Define the Array or list of objects at run time
#include &lt;vector&gt;
std::string val;
std::vector&lt;string&gt; my_vector; // initialize the vector
std::cin &gt;&gt; val;

my_vector.push_back(val); // will push the value of 'val' into vector ("array") my_vector
my_vector.push_back(val); // will push the value into the vector again (now having two elements)

// To iterate through a vector we have 2 choices:
// Either classic looping (iterating through the vector from index 0 to its last index):
for (int i = 0; i &lt; my_vector.size(); i++) {
    std::cout &lt;&lt; my_vector[i] &lt;&lt; '\n'; // for accessing a vector's element we can use the operator []
}

// or using an iterator:
vector&lt;string&gt;::iterator it; // initialize the iterator for vector
for (it = my_vector.begin(); it != my_vector.end(); ++it) {
    std::cout &lt;&lt; *it  &lt;&lt; '\n';
}

// Set
// Sets are containers that store unique elements following a specific order.
// Set is a very useful container to store unique values in sorted order
// without any other functions or code.

#include&lt;set&gt;
std::set&lt;int&gt; ST;    // Will initialize the set of int data type
ST.insert(30);  // Will insert the value 30 in set ST
ST.insert(10);  // Will insert the value 10 in set ST
ST.insert(20);  // Will insert the value 20 in set ST
ST.insert(30);  // Will insert the value 30 in set ST
// Now elements of sets are as follows
//  10 20 30

// To erase an element
ST.erase(20);  // Will erase element with value 20
// Set ST: 10 30
// To iterate through Set we use iterators
std::set&lt;int&gt;::iterator it;
for (it = ST.begin(); it != ST.end(); it++) {
    std::cout &lt;&lt; *it &lt;&lt; '\n';
}
// Output:
// 10
// 30

// To clear the complete container we use Container_name.clear()
ST.clear();
std::cout &lt;&lt; ST.size();  // will print the size of set ST
// Output: 0

// NOTE: for duplicate elements we can use multiset
// NOTE: For hash sets, use unordered_set. They are more efficient but
// do not preserve order. unordered_set is available since C++11

// Map
// Maps store elements formed by a combination of a key value
// and a mapped value, following a specific order.

#include&lt;map&gt;
std::map&lt;char, int&gt; mymap;  // Will initialize the map with key as char and value as int

mymap.insert(pair&lt;char,int&gt;('A',1));
// Will insert value 1 for key A
mymap.insert(pair&lt;char,int&gt;('Z',26));
// Will insert value 26 for key Z

// To iterate
std::map&lt;char,int&gt;::iterator it;
for (it = mymap.begin(); it != mymap.end(); ++it)
    std::cout &lt;&lt; it-&gt;first &lt;&lt; "-&gt;" &lt;&lt; it-&gt;second &lt;&lt; '\n';
// Output:
// A-&gt;1
// Z-&gt;26

// To find the value corresponding to a key
it = mymap.find('Z');
std::cout &lt;&lt; it-&gt;second;

// Output: 26

// NOTE: For hash maps, use unordered_map. They are more efficient but do
// not preserve order. unordered_map is available since C++11.

// Containers with object keys of non-primitive values (custom classes) require
// compare function in the object itself or as a function pointer. Primitives
// have default comparators, but you can override it.
class Foo {
public:
    int j;
    Foo(int a) : j(a) {}
};
struct compareFunction {
    bool operator()(const Foo&amp; a, const Foo&amp; b) const {
        return a.j &lt; b.j;
    }
};
// this isn't allowed (although it can vary depending on compiler)
// std::map&lt;Foo, int&gt; fooMap;
std::map&lt;Foo, int, compareFunction&gt; fooMap;
fooMap[Foo(1)]  = 1;
fooMap.find(Foo(1)); //true


///////////////////////////////////////
// Lambda Expressions (C++11 and above)
///////////////////////////////////////

// lambdas are a convenient way of defining an anonymous function
// object right at the location where it is invoked or passed as
// an argument to a function.

// For example, consider sorting a vector of pairs using the second
// value of the pair

std::vector&lt;pair&lt;int, int&gt; &gt; tester;
tester.push_back(make_pair(3, 6));
tester.push_back(make_pair(1, 9));
tester.push_back(make_pair(5, 0));

// Pass a lambda expression as third argument to the sort function
// sort is from the &lt;algorithm&gt; header

std::sort(tester.begin(), tester.end(), [](const pair&lt;int, int&gt;&amp; lhs, const pair&lt;int, int&gt;&amp; rhs) {
        return lhs.second &lt; rhs.second;
    });

// Notice the syntax of the lambda expression,
// [] in the lambda is used to "capture" variables
// The "Capture List" defines what from the outside of the lambda should be available inside the function body and how.
// It can be either:
//     1. a value : [x]
//     2. a reference : [&amp;x]
//     3. any variable currently in scope by reference [&amp;]
//     4. same as 3, but by value [=]
// Example:

std::vector&lt;int&gt; dog_ids;
// number_of_dogs = 3;
for (int i = 0; i &lt; 3; i++) {
    dog_ids.push_back(i);
}

int weight[3] = {30, 50, 10};

// Say you want to sort dog_ids according to the dogs' weights
// So dog_ids should in the end become: [2, 0, 1]

// Here's where lambda expressions come in handy

sort(dog_ids.begin(), dog_ids.end(), [&amp;weight](const int &amp;lhs, const int &amp;rhs) {
        return weight[lhs] &lt; weight[rhs];
    });
// Note we captured "weight" by reference in the above example.
// More on Lambdas in C++ : https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11

///////////////////////////////
// Range For (C++11 and above)
///////////////////////////////

// You can use a range for loop to iterate over a container
int arr[] = {1, 10, 3};

for (int elem: arr) {
    cout &lt;&lt; elem &lt;&lt; endl;
}

// You can use "auto" and not worry about the type of the elements of the container
// For example:

for (auto elem: arr) {
    // Do something with each element of arr
}

/////////////////////
// Fun stuff
/////////////////////

// Aspects of C++ that may be surprising to newcomers (and even some veterans).
// This section is, unfortunately, wildly incomplete; C++ is one of the easiest
// languages with which to shoot yourself in the foot.

// You can override private methods!
class Foo {
    virtual void bar();
};
class FooSub : public Foo {
    virtual void bar();  // Overrides Foo::bar!
};


// 0 == false == NULL (most of the time)!
bool* pt = new bool;
*pt = 0; // Sets the value points by 'pt' to false.
pt = 0;  // Sets 'pt' to the null pointer. Both lines compile without warnings.

// nullptr is supposed to fix some of that issue:
int* pt2 = new int;
*pt2 = nullptr; // Doesn't compile
pt2 = nullptr;  // Sets pt2 to null.

// There is an exception made for bools.
// This is to allow you to test for null pointers with if(!ptr),
// but as a consequence you can assign nullptr to a bool directly!
*pt = nullptr;  // This still compiles, even though '*pt' is a bool!


// '=' != '=' != '='!
// Calls Foo::Foo(const Foo&amp;) or some variant (see move semantics) copy
// constructor.
Foo f2;
Foo f1 = f2;

// Calls Foo::Foo(const Foo&amp;) or variant, but only copies the 'Foo' part of
// 'fooSub'. Any extra members of 'fooSub' are discarded. This sometimes
// horrifying behavior is called "object slicing."
FooSub fooSub;
Foo f1 = fooSub;

// Calls Foo::operator=(Foo&amp;) or variant.
Foo f1;
f1 = f2;


///////////////////////////////////////
// Tuples (C++11 and above)
///////////////////////////////////////

#include&lt;tuple&gt;

// Conceptually, Tuples are similar to old data structures (C-like structs)
// but instead of having named data members,
// its elements are accessed by their order in the tuple.

// We start with constructing a tuple.
// Packing values into tuple
auto first = make_tuple(10, 'A');
const int maxN = 1e9;
const int maxL = 15;
auto second = make_tuple(maxN, maxL);

// Printing elements of 'first' tuple
std::cout &lt;&lt; get&lt;0&gt;(first) &lt;&lt; " " &lt;&lt; get&lt;1&gt;(first) &lt;&lt; '\n'; //prints : 10 A

// Printing elements of 'second' tuple
std::cout &lt;&lt; get&lt;0&gt;(second) &lt;&lt; " " &lt;&lt; get&lt;1&gt;(second) &lt;&lt; '\n'; // prints: 1000000000 15

// Unpacking tuple into variables

int first_int;
char first_char;
tie(first_int, first_char) = first;
std::cout &lt;&lt; first_int &lt;&lt; " " &lt;&lt; first_char &lt;&lt; '\n';  // prints : 10 A

// We can also create tuple like this.

tuple&lt;int, char, double&gt; third(11, 'A', 3.14141);
// tuple_size returns number of elements in a tuple (as a constexpr)

std::cout &lt;&lt; tuple_size&lt;decltype(third)&gt;::value &lt;&lt; '\n'; // prints: 3

// tuple_cat concatenates the elements of all the tuples in the same order.

auto concatenated_tuple = tuple_cat(first, second, third);
// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A', 3.14141)

std::cout &lt;&lt; get&lt;0&gt;(concatenated_tuple) &lt;&lt; '\n'; // prints: 10
std::cout &lt;&lt; get&lt;3&gt;(concatenated_tuple) &lt;&lt; '\n'; // prints: 15
std::cout &lt;&lt; get&lt;5&gt;(concatenated_tuple) &lt;&lt; '\n'; // prints: 'A'


///////////////////////////////////
// Logical and Bitwise operators
//////////////////////////////////

// Most of the operators in C++ are same as in other languages

// Logical operators

// C++ uses Short-circuit evaluation for boolean expressions, i.e, the second argument is executed or
// evaluated only if the first argument does not suffice to determine the value of the expression

true &amp;&amp; false // Performs **logical and** to yield false
true || false // Performs **logical or** to yield true
! true        // Performs **logical not** to yield false

// Instead of using symbols equivalent keywords can be used
true and false // Performs **logical and** to yield false
true or false  // Performs **logical or** to yield true
not true       // Performs **logical not** to yield false

// Bitwise operators

// **&lt;&lt;** Left Shift Operator
// &lt;&lt; shifts bits to the left
4 &lt;&lt; 1 // Shifts bits of 4 to left by 1 to give 8
// x &lt;&lt; n can be thought as x * 2^n


// **&gt;&gt;** Right Shift Operator
// &gt;&gt; shifts bits to the right
4 &gt;&gt; 1 // Shifts bits of 4 to right by 1 to give 2
// x &gt;&gt; n can be thought as x / 2^n

~4    // Performs a bitwise not
4 | 3 // Performs bitwise or
4 &amp; 3 // Performs bitwise and
4 ^ 3 // Performs bitwise xor

// Equivalent keywords are
compl 4    // Performs a bitwise not
4 bitor 3  // Performs bitwise or
4 bitand 3 // Performs bitwise and
4 xor 3    // Performs bitwise xor
</code></pre>
<p>Go:</p>
<pre><code class="lang-plaintext">// Single line comment
/* Multi-
 line comment */

 /* A build tag is a line comment starting with //go:build
  and can be executed by go build -tags="foo bar" command.
  Build tags are placed before the package clause near or at the top of the file
  followed by a blank line or other line comments. */
//go:build prod || dev || test

// A package clause starts every source file.
// main is a special name declaring an executable rather than a library.
package main

// Import declaration declares library packages referenced in this file.
import (
    "fmt"              // A package in the Go standard library.
    "io"               // Implements some I/O utility functions.
    m "math"           // Math library with local alias m.
    "net/http"         // Yes, a web server!
    _ "net/http/pprof" // Profiling library imported only for side effects
    "os"               // OS functions like working with the file system
    "strconv"          // String conversions.
)

// A function definition. Main is special. It is the entry point for the
// executable program. Love it or hate it, Go uses brace brackets.
func main() {
    // Println outputs a line to stdout.
    // It comes from the package fmt.
    fmt.Println("Hello world!")

    // Call another function within this package.
    beyondHello()
}

// Functions have parameters in parentheses.
// If there are no parameters, empty parentheses are still required.
func beyondHello() {
    var x int // Variable declaration. Variables must be declared before use.
    x = 3     // Variable assignment.
    // "Short" declarations use := to infer the type, declare, and assign.
    y := 4
    sum, prod := learnMultiple(x, y)        // Function returns two values.
    fmt.Println("sum:", sum, "prod:", prod) // Simple output.
    learnTypes()                            // &lt; y minutes, learn more!
}

/* &lt;- multiline comment
Functions can have parameters and (multiple!) return values.
Here `x`, `y` are the arguments and `sum`, `prod` is the signature (what's returned).
Note that `x` and `sum` receive the type `int`.
*/
func learnMultiple(x, y int) (sum, prod int) {
    return x + y, x * y // Return two values.
}

// Some built-in types and literals.
func learnTypes() {
    // Short declaration usually gives you what you want.
    str := "Learn Go!" // string type.

    s2 := `A "raw" string literal
can include line breaks.` // Same string type.

    // Non-ASCII literal. Go source is UTF-8.
    g := 'Σ' // rune type, an alias for int32, holds a unicode code point.

    f := 3.14159 // float64, an IEEE-754 64-bit floating point number.
    c := 3 + 4i  // complex128, represented internally with two float64's.

    // var syntax with initializers.
    var u uint = 7 // Unsigned, but implementation dependent size as with int.
    var pi float32 = 22. / 7

    // Conversion syntax with a short declaration.
    n := byte('\n') // byte is an alias for uint8.

    // Arrays have size fixed at compile time.
    var a4 [4]int                    // An array of 4 ints, initialized to all 0.
    a5 := [...]int{3, 1, 5, 10, 100} // An array initialized with a fixed size of five
    // elements, with values 3, 1, 5, 10, and 100.

    // Arrays have value semantics.
    a4_cpy := a4                    // a4_cpy is a copy of a4, two separate instances.
    a4_cpy[0] = 25                  // Only a4_cpy is changed, a4 stays the same.
    fmt.Println(a4_cpy[0] == a4[0]) // false

    // Slices have dynamic size. Arrays and slices each have advantages
    // but use cases for slices are much more common.
    s3 := []int{4, 5, 9}    // Compare to a5. No ellipsis here.
    s4 := make([]int, 4)    // Allocates slice of 4 ints, initialized to all 0.
    var d2 [][]float64      // Declaration only, nothing allocated here.
    bs := []byte("a slice") // Type conversion syntax.

    // Slices (as well as maps and channels) have reference semantics.
    s3_cpy := s3                    // Both variables point to the same instance.
    s3_cpy[0] = 0                   // Which means both are updated.
    fmt.Println(s3_cpy[0] == s3[0]) // true

    // Because they are dynamic, slices can be appended to on-demand.
    // To append elements to a slice, the built-in append() function is used.
    // First argument is a slice to which we are appending. Commonly,
    // the slice variable is updated in place, as in example below.
    s := []int{1, 2, 3}    // Result is a slice of length 3.
    s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
    fmt.Println(s)         // Updated slice is now [1 2 3 4 5 6]

    // To append another slice, instead of list of atomic elements we can
    // pass a reference to a slice or a slice literal like this, with a
    // trailing ellipsis, meaning take a slice and unpack its elements,
    // appending them to slice s.
    s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal.
    fmt.Println(s)                   // Updated slice is now [1 2 3 4 5 6 7 8 9]

    p, q := learnMemory() // Declares p, q to be type pointer to int.
    fmt.Println(*p, *q)   // * follows a pointer. This prints two ints.

    // Maps are a dynamically growable associative array type, like the
    // hash or dictionary types of some other languages.
    m := map[string]int{"three": 3, "four": 4}
    m["one"] = 1
    // Looking up a missing key returns the zero value,
    // which is 0 in this case, since it's a map[string]int
    m["key not present"] // 0
    // Check if a key is present in the map like this:
    if val, ok := m["one"]; ok {
        // Do something
    }

    // Unused variables are an error in Go.
    // The underscore lets you "use" a variable but discard its value.
    _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a5, s4, bs
    // Usually you use it to ignore one of the return values of a function
    // For example, in a quick and dirty script you might ignore the
    // error value returned from os.Create, and expect that the file
    // will always be created.
    file, _ := os.Create("output.txt")
    fmt.Fprint(file, "This is how you write to a file, by the way")
    file.Close()

    // Output of course counts as using a variable.
    fmt.Println(s, c, a4, s3, d2, m)

    learnFlowControl() // Back in the flow.
}

// It is possible, unlike in many other languages for functions in go
// to have named return values.
// Assigning a name to the type being returned in the function declaration line
// allows us to easily return from multiple points in a function as well as to
// only use the return keyword, without anything further.
func learnNamedReturns(x, y int) (z int) {
    z = x * y
    return // z is implicit here, because we named it earlier.
}

// Go is fully garbage collected. It has pointers but no pointer arithmetic.
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
// Unlike in C/Cpp taking and returning an address of a local variable is also safe.
func learnMemory() (p, q *int) {
    // Named return values p and q have type pointer to int.
    p = new(int) // Built-in function new allocates memory.
    // The allocated int slice is initialized to 0, p is no longer nil.
    s := make([]int, 20) // Allocate 20 ints as a single block of memory.
    s[3] = 7             // Assign one of them.
    r := -2              // Declare another local variable.
    return &amp;s[3], &amp;r     // &amp; takes the address of an object.
}

// Use the aliased math library (see imports, above)
func expensiveComputation() float64 {
    return m.Exp(10)
}

func learnFlowControl() {
    // If statements require brace brackets, and do not require parentheses.
    if true {
        fmt.Println("told ya")
    }
    // Formatting is standardized by the command line command "go fmt".
    if false {
        // Pout.
    } else {
        // Gloat.
    }
    // Use switch in preference to chained if statements.
    x := 42.0
    switch x {
    case 0:
    case 1, 2: // Can have multiple matches on one case
    case 42:
        // Cases don't "fall through".
        /*
            There is a `fallthrough` keyword however, see:
            https://go.dev/wiki/Switch#fall-through
        */
    case 43:
        // Unreached.
    default:
        // Default case is optional.
    }

    // Type switch allows switching on the type of something instead of value
    var data interface{}
    data = ""
    switch c := data.(type) {
    case string:
        fmt.Println(c, "is a string")
    case int64:
        fmt.Printf("%d is an int64\n", c)
    default:
        // all other cases
    }

    // Like if, for doesn't use parens either.
    // Variables declared in for and if are local to their scope.
    for x := 0; x &lt; 3; x++ { // ++ is a statement.
        fmt.Println("iteration", x)
    }
    // x == 42 here.

    // For is the only loop statement in Go, but it has alternate forms.
    for { // Infinite loop.
        break    // Just kidding.
        continue // Unreached.
    }

    // You can use range to iterate over an array, a slice, a string, a map, or a channel.
    // range returns one (channel) or two values (array, slice, string and map).
    for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} {
        // for each pair in the map, print key and value
        fmt.Printf("key=%s, value=%d\n", key, value)
    }
    // If you only need the value, use the underscore as the key
    for _, name := range []string{"Bob", "Bill", "Joe"} {
        fmt.Printf("Hello, %s\n", name)
    }

    // As with for, := in an if statement means to declare and assign
    // y first, then test y &gt; x.
    if y := expensiveComputation(); y &gt; x {
        x = y
    }
    // Function literals are closures.
    xBig := func() bool {
        return x &gt; 10000 // References x declared above switch statement.
    }
    x = 99999
    fmt.Println("xBig:", xBig()) // true
    x = 1.3e3                    // This makes x == 1300
    fmt.Println("xBig:", xBig()) // false now.

    // What's more is function literals may be defined and called inline,
    // acting as an argument to function, as long as:
    // a) function literal is called immediately (),
    // b) result type matches expected type of argument.
    fmt.Println("Add + double two numbers: ",
        func(a, b int) int {
            return (a + b) * 2
        }(10, 2)) // Called with args 10 and 2
    // =&gt; Add + double two numbers: 24

    // When you need it, you'll love it.
    goto love
love:

    learnFunctionFactory() // func returning func is fun(3)(3)
    learnDefer()      // A quick detour to an important keyword.
    learnInterfaces() // Good stuff coming up!
}

func learnFunctionFactory() {
    // Next two are equivalent, with second being more practical
    fmt.Println(sentenceFactory("summer")("A beautiful", "day!"))

    d := sentenceFactory("summer")
    fmt.Println(d("A beautiful", "day!"))
    fmt.Println(d("A lazy", "afternoon!"))
}

// Decorators are common in other languages. Same can be done in Go
// with function literals that accept arguments.
func sentenceFactory(mystring string) func(before, after string) string {
    return func(before, after string) string {
        return fmt.Sprintf("%s %s %s", before, mystring, after) // new string
    }
}

func learnDefer() (ok bool) {
    // A defer statement pushes a function call onto a list. The list of saved
    // calls is executed AFTER the surrounding function returns.
    defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
    defer fmt.Println("\nThis line is being printed first because")
    // Defer is commonly used to close a file, so the function closing the
    // file stays near the function opening the file.
    return true
}

// Define Stringer as an interface type with one method, String.
type Stringer interface {
    String() string
}

// Define pair as a struct with two fields, ints named x and y.
type pair struct {
    x, y int
}

// Define a method on type pair. Pair now implements Stringer because Pair has defined all the methods in the interface.
func (p pair) String() string { // p is called the "receiver"
    // Sprintf is another public function in package fmt.
    // Dot syntax references fields of p.
    return fmt.Sprintf("(%d, %d)", p.x, p.y)
}

func learnInterfaces() {
    // Brace syntax is a "struct literal". It evaluates to an initialized
    // struct. The := syntax declares and initializes p to this struct.
    p := pair{3, 4}
    fmt.Println(p.String()) // Call String method of p, of type pair.
    var i Stringer          // Declare i of interface type Stringer.
    i = p                   // Valid because pair implements Stringer
    // Call String method of i, of type Stringer. Output same as above.
    fmt.Println(i.String())

    // Functions in the fmt package call the String method to ask an object
    // for a printable representation of itself.
    fmt.Println(p) // Output same as above. Println calls String method.
    fmt.Println(i) // Output same as above.

    learnVariadicParams("great", "learning", "here!")
}

// Functions can have variadic parameters.
func learnVariadicParams(myStrings ...any) { // any is an alias for interface{}
    // Iterate each value of the variadic.
    // The underscore here is ignoring the index argument of the array.
    for _, param := range myStrings {
        fmt.Println("param:", param)
    }

    // Pass variadic value as a variadic parameter.
    fmt.Println("params:", fmt.Sprintln(myStrings...))

    learnErrorHandling()
}

func learnErrorHandling() {
    // ", ok" idiom used to tell if something worked or not.
    m := map[int]string{3: "three", 4: "four"}
    if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map.
        fmt.Println("no one there")
    } else {
        fmt.Print(x) // x would be the value, if it were in the map.
    }
    // An error value communicates not just "ok" but more about the problem.
    if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
        // prints 'strconv.ParseInt: parsing "non-int": invalid syntax'
        fmt.Println(err)
    }
    // We'll revisit interfaces a little later. Meanwhile,
    learnConcurrency()
}

// c is a channel, a concurrency-safe communication object.
func inc(i int, c chan int) {
    c &lt;- i + 1 // &lt;- is the "send" operator when a channel appears on the left.
}

// We'll use inc to increment some numbers concurrently.
func learnConcurrency() {
    // Same make function used earlier to make a slice. Make allocates and
    // initializes slices, maps, and channels.
    c := make(chan int)
    // Start three concurrent goroutines. Numbers will be incremented
    // concurrently, perhaps in parallel if the machine is capable and
    // properly configured. All three send to the same channel.
    go inc(0, c) // go is a statement that starts a new goroutine.
    go inc(10, c)
    go inc(-805, c)
    // Read three results from the channel and print them out.
    // There is no telling in what order the results will arrive!
    fmt.Println(&lt;-c, &lt;-c, &lt;-c) // channel on right, &lt;- is "receive" operator.

    cs := make(chan string)       // Another channel, this one handles strings.
    ccs := make(chan chan string) // A channel of string channels.
    go func() { c &lt;- 84 }()       // Start a new goroutine just to send a value.
    go func() { cs &lt;- "wordy" }() // Again, for cs this time.
    // Select has syntax like a switch statement but each case involves
    // a channel operation. It selects a case at random out of the cases
    // that are ready to communicate.
    select {
    case i := &lt;-c: // The value received can be assigned to a variable,
        fmt.Printf("it's a %T", i)
    case &lt;-cs: // or the value received can be discarded.
        fmt.Println("it's a string")
    case &lt;-ccs: // Empty channel, not ready for communication.
        fmt.Println("didn't happen.")
    }
    // At this point a value was taken from either c or cs. One of the two
    // goroutines started above has completed, the other will remain blocked.

    learnWebProgramming() // Go does it. You want to do it too.
}

// A single function from package http starts a web server.
func learnWebProgramming() {
    // First parameter of ListenAndServe is TCP address to listen to.
    // Second parameter is an interface, specifically http.Handler.
    go func() {
        err := http.ListenAndServe(":8080", pair{})
        fmt.Println(err) // don't ignore errors
    }()

    requestServer()
}

// Make pair an http.Handler by implementing its only method, ServeHTTP.
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // Serve data with a method of http.ResponseWriter.
    w.Write([]byte("You learned Go in Y minutes!"))
}

func requestServer() {
    resp, err := http.Get("http://localhost:8080")
    fmt.Println(err)
    defer resp.Body.Close()
    body, err := io.ReadAll(resp.Body)
    fmt.Printf("\nWebserver said: `%s`", string(body))
}
</code></pre>
<p>Java:</p>
<pre><code class="lang-plaintext">// Single-line comments start with //

/*
Multi-line comments look like this.
*/

/**
 * JavaDoc comments look like this. Used to describe the Class or various
 * attributes of a Class.
 * Main attributes:
 *
 * @author         Name (and contact information such as email) of author(s).
 * @version     Current version of the program.
 * @since        When this part of the program was first added.
 * @param         For describing the different parameters for a method.
 * @return        For describing what the method returns.
 * @deprecated  For showing the code is outdated or shouldn't be used.
 * @see         Links to another part of documentation.
*/

// Import ArrayList class inside of the java.util package
import java.util.ArrayList;
// Import all classes inside of java.security package
import java.security.*;
// Java to illustrate calling of static members and methods without calling classname
import static java.lang.Math.*;
import static java.lang.System.*;

public class LearnJava {

    // In order to run a java program, it must have a main method as an entry
    // point.
    public static void main(String[] args) {

    ///////////////////////////////////////
    // Input/Output
    ///////////////////////////////////////

        /*
        * Output
        */

        // Use System.out.println() to print lines.
        System.out.println("Hello World!");
        System.out.println(
            "Integer: " + 10 +
            " Double: " + 3.14 +
            " Boolean: " + true);

        // To print without a newline, use System.out.print().
        System.out.print("Hello ");
        System.out.print("World");

        // Use System.out.printf() for easy formatted printing.
        System.out.printf("pi = %.5f", Math.PI); // =&gt; pi = 3.14159

        /*
         * Input
         */

        // use Scanner to read input
        // must import java.util.Scanner;
        Scanner scanner = new Scanner(System.in);

        // read string input
        String name = scanner.next();

        // read byte input
        byte numByte = scanner.nextByte();

        // read int input
        int numInt = scanner.nextInt();

        // read long input
        long numLong = scanner.nextLong();

        // read float input
        float numFloat = scanner.nextFloat();

        // read double input
        double numDouble = scanner.nextDouble();

        // read boolean input
        boolean bool = scanner.nextBoolean();

        ///////////////////////////////////////
        // Variables
        ///////////////////////////////////////

        /*
        *  Variable Declaration
        */
        // Declare a variable using &lt;type&gt; &lt;name&gt;
        int fooInt;
        // Declare multiple variables of the same
        // type &lt;type&gt; &lt;name1&gt;, &lt;name2&gt;, &lt;name3&gt;
        int fooInt1, fooInt2, fooInt3;

        /*
        *  Variable Initialization
        */

        // Initialize a variable using &lt;type&gt; &lt;name&gt; = &lt;val&gt;
        int barInt = 1;
        // Initialize multiple variables of same type with same
        // value &lt;type&gt; &lt;name1&gt;, &lt;name2&gt;, &lt;name3&gt;
        // &lt;name1&gt; = &lt;name2&gt; = &lt;name3&gt; = &lt;val&gt;
        int barInt1, barInt2, barInt3;
        barInt1 = barInt2 = barInt3 = 1;
        // Shorthand for multiple declarations
        int barInt4 = 1, barInt5 = 2; 


        /*
        *  Variable types
        */
        // Byte - 8-bit signed two's complement integer
        // (-128 &lt;= byte &lt;= 127)
        byte fooByte = 100;

        // If you would like to interpret a byte as an unsigned integer
        // then this simple operation can help
        int unsignedIntLessThan256 = 0xff &amp; fooByte;
        // this contrasts a cast which can be negative.
        int signedInt = (int) fooByte;

        // Short - 16-bit signed two's complement integer
        // (-32,768 &lt;= short &lt;= 32,767)
        short fooShort = 10000;

        // Integer - 32-bit signed two's complement integer
        // (-2,147,483,648 &lt;= int &lt;= 2,147,483,647)
        int bazInt = 1;

        // Long - 64-bit signed two's complement integer
        // (-9,223,372,036,854,775,808 &lt;= long &lt;= 9,223,372,036,854,775,807)
        long fooLong = 100000L;
        // L is used to denote that this variable value is of type Long;
        // anything without is treated as integer by default.

        // Note: byte, short, int and long are signed. They can have positive and negative values.
        // There are no unsigned variants.
        // char, however, is 16-bit unsigned.

        // Float - Single-precision 32-bit IEEE 754 Floating Point
        // 2^-149 &lt;= float &lt;= (2-2^-23) * 2^127
        float fooFloat = 234.5f;
        // f or F is used to denote that this variable value is of type float;
        // otherwise it is treated as double.

        // Double - Double-precision 64-bit IEEE 754 Floating Point
        // 2^-1074 &lt;= x &lt;= (2-2^-52) * 2^1023
        double fooDouble = 123.4;

        // Boolean - true &amp; false
        boolean fooBoolean = true;
        boolean barBoolean = false;

        // Char - A single 16-bit Unicode character
        char fooChar = 'A';

        // final variables can't be reassigned,
        final int HOURS_I_WORK_PER_WEEK = 9001;
        // but they can be initialized later.
        final double E;
        E = 2.71828;

        // BigInteger - Immutable arbitrary-precision integers
        //
        // BigInteger is a data type that allows programmers to manipulate
        // integers longer than 64-bits. Integers are stored as an array of
        // bytes and are manipulated using functions built into BigInteger
        //
        // BigInteger can be initialized using an array of bytes or a string.
        BigInteger fooBigInteger = new BigInteger(fooByteArray);

        // BigDecimal - Immutable, arbitrary-precision signed decimal number
        //
        // A BigDecimal takes two parts: an arbitrary precision integer
        // unscaled value and a 32-bit integer scale
        //
        // BigDecimal allows the programmer complete control over decimal
        // rounding. It is recommended to use BigDecimal with currency values
        // and where exact decimal precision is required.
        //
        // BigDecimal can be initialized with an int, long, double or String
        // or by initializing the unscaled value (BigInteger) and scale (int).
        BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);

        // Be wary of the constructor that takes a float or double as
        // the inaccuracy of the float/double will be copied in BigDecimal.
        // Prefer the String constructor when you need an exact value.
        BigDecimal tenCents = new BigDecimal("0.1");

        // Type inference with 'var'
        var x = 100; // int
        var y = 1.90; // double
        var z = 'a'; // char
        var p = "tanu"; // String
        var q = false; // boolean

        // Strings
        String fooString = "My String Is Here!";

        // Text blocks
        var textBlock = """
                        This is a &lt;Text Block&gt; in Java 
                        """;

        // \n is an escaped character that starts a new line
        String barString = "Printing on a new line?\nNo Problem!";
        // \t is an escaped character that adds a tab character
        String bazString = "Do you want to add a tab?\tNo Problem!";
        System.out.println(fooString);
        System.out.println(barString);
        System.out.println(bazString);

        // String Building
        // #1 - with plus operator
        // That's the basic way to do it (optimized under the hood)
        String plusConcatenated = "Strings can " + "be concatenated " + "via + operator.";
        System.out.println(plusConcatenated);
        // Output: Strings can be concatenated via + operator.

        // #2 - with StringBuilder
        // This way doesn't create any intermediate strings. It just stores the string pieces, and ties them together
        // when toString() is called.
        // Hint: This class is not thread safe. A thread-safe alternative (with some impact on performance) is StringBuffer.
        StringBuilder builderConcatenated = new StringBuilder();
        builderConcatenated.append("You ");
        builderConcatenated.append("can use ");
        builderConcatenated.append("the StringBuilder class.");
        System.out.println(builderConcatenated.toString()); // only now is the string built
        // Output: You can use the StringBuilder class.

        // StringBuilder is efficient when the fully constructed String is not required until the end of some processing.
        StringBuilder stringBuilder = new StringBuilder();
        String inefficientString = "";
        for (int i = 0 ; i &lt; 10; i++) {
            stringBuilder.append(i).append(" ");
            inefficientString += i + " ";
        }
        System.out.println(inefficientString);
        System.out.println(stringBuilder.toString());
        // inefficientString requires a lot more work to produce, as it generates a String on every loop iteration.
        // Simple concatenation with + is compiled to a StringBuilder and toString()
        // Avoid string concatenation in loops.

        // #3 - with String formatter
        // Another alternative way to create strings. Fast and readable.
        String.format("%s may prefer %s.", "Or you", "String.format()");
        // Output: Or you may prefer String.format().

        // Arrays
        // The array size must be decided upon instantiation
        // The following formats work for declaring an array
        // &lt;datatype&gt;[] &lt;var name&gt; = new &lt;datatype&gt;[&lt;array size&gt;];
        // &lt;datatype&gt; &lt;var name&gt;[] = new &lt;datatype&gt;[&lt;array size&gt;];
        int[] intArray = new int[10];
        String[] stringArray = new String[1];
        boolean boolArray[] = new boolean[100];

        // Another way to declare &amp; initialize an array
        int[] y = {9000, 1000, 1337};
        String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
        boolean bools[] = {true, false, false};

        // Indexing an array - Accessing an element
        System.out.println("intArray @ 0: " + intArray[0]);

        // Arrays are zero-indexed and mutable.
        intArray[1] = 1;
        System.out.println("intArray @ 1: " + intArray[1]); // =&gt; 1

        // Other data types worth checking out
        // ArrayLists - Like arrays except more functionality is offered, and
        //              the size is mutable.
        // LinkedLists - Implementation of doubly-linked list. All of the
        //               operations perform as could be expected for a
        //               doubly-linked list.
        // Maps - A mapping of key Objects to value Objects. Map is
        //        an interface and therefore cannot be instantiated.
        //        The type of keys and values contained in a Map must
        //        be specified upon instantiation of the implementing
        //        class. Each key may map to only one corresponding value,
        //        and each key may appear only once (no duplicates).
        // HashMaps - This class uses a hashtable to implement the Map
        //            interface. This allows the execution time of basic
        //            operations, such as get and insert element, to remain
        //            constant-amortized even for large sets.
        // TreeMap - A Map that is sorted by its keys. Each modification
        //           maintains the sorting defined by either a Comparator
        //           supplied at instantiation, or comparisons of each Object
        //           if they implement the Comparable interface.
        //           Failure of keys to implement Comparable combined with failure to
        //           supply a Comparator will throw ClassCastExceptions.
        //           Insertion and removal operations take O(log(n)) time
        //           so avoid using this data structure unless you are taking
        //           advantage of the sorting.

        ///////////////////////////////////////
        // Operators
        ///////////////////////////////////////
        System.out.println("\n-&gt;Operators");

        int i1 = 1, i2 = 2;

        // Arithmetic is straightforward
        System.out.println("1+2 = " + (i1 + i2)); // =&gt; 3
        System.out.println("2-1 = " + (i2 - i1)); // =&gt; 1
        System.out.println("2*1 = " + (i2 * i1)); // =&gt; 2
        System.out.println("1/2 = " + (i1 / i2)); // =&gt; 0 (int/int returns int)
        System.out.println("1/2.0 = " + (i1 / (double)i2)); // =&gt; 0.5

        // Modulo
        System.out.println("11%3 = " + (11 % 3)); // =&gt; 2

        // Comparison operators
        System.out.println("3 == 2? " + (3 == 2)); // =&gt; false
        System.out.println("3 != 2? " + (3 != 2)); // =&gt; true
        System.out.println("3 &gt; 2? " + (3 &gt; 2)); // =&gt; true
        System.out.println("3 &lt; 2? " + (3 &lt; 2)); // =&gt; false
        System.out.println("2 &lt;= 2? " + (2 &lt;= 2)); // =&gt; true
        System.out.println("2 &gt;= 2? " + (2 &gt;= 2)); // =&gt; true

        // Boolean operators
        System.out.println("3 &gt; 2 &amp;&amp; 2 &gt; 3? " + ((3 &gt; 2) &amp;&amp; (2 &gt; 3))); // =&gt; false
        System.out.println("3 &gt; 2 || 2 &gt; 3? " + ((3 &gt; 2) || (2 &gt; 3))); // =&gt; true
        System.out.println("!(3 == 2)? " + (!(3 == 2))); // =&gt; true

        // Bitwise operators!
        /*
        ~      Unary bitwise complement
        &lt;&lt;     Signed left shift
        &gt;&gt;     Signed/Arithmetic right shift
        &gt;&gt;&gt;    Unsigned/Logical right shift
        &amp;      Bitwise AND
        ^      Bitwise exclusive OR
        |      Bitwise inclusive OR
        */

        // Increment operators
        int i = 0;
        System.out.println("\n-&gt;Inc/Dec-rementation");
        // The ++ and -- operators increment and decrement by 1 respectively.
        // If they are placed before the variable, they increment then return;
        // after the variable they return then increment.
        System.out.println(i++); // i = 1, prints 0 (post-increment)
        System.out.println(++i); // i = 2, prints 2 (pre-increment)
        System.out.println(i--); // i = 1, prints 2 (post-decrement)
        System.out.println(--i); // i = 0, prints 0 (pre-decrement)

        ///////////////////////////////////////
        // Control Structures
        ///////////////////////////////////////
        System.out.println("\n-&gt;Control Structures");

        // If statements are c-like
        int j = 10;
        if (j == 10) {
            System.out.println("I get printed");
        } else if (j &gt; 10) {
            System.out.println("I don't");
        } else {
            System.out.println("I also don't");
        }

        // While loop
        int fooWhile = 0;
        while (fooWhile &lt; 100) {
            System.out.println(fooWhile);
            // Increment the counter
            // Iterated 100 times, fooWhile 0,1,2...99
            fooWhile++;
        }
        System.out.println("fooWhile Value: " + fooWhile);

        // Do While Loop
        int fooDoWhile = 0;
        do {
            System.out.println(fooDoWhile);
            // Increment the counter
            // Iterated 100 times, fooDoWhile 0-&gt;99
            fooDoWhile++;
        } while (fooDoWhile &lt; 100);
        System.out.println("fooDoWhile Value: " + fooDoWhile);

        // For Loop
        // for loop structure =&gt; for(&lt;start_statement&gt;; &lt;conditional&gt;; &lt;step&gt;)
        for (int fooFor = 0; fooFor &lt; 10; fooFor++) {
            System.out.println(fooFor);
            // Iterated 10 times, fooFor 0-&gt;9
        }
        System.out.println("fooFor Value: " + fooFor);

        // Nested For Loop Exit with Label
        outer:
        for (int i = 0; i &lt; 10; i++) {
          for (int j = 0; j &lt; 10; j++) {
            if (i == 5 &amp;&amp; j ==5) {
              break outer;
              // breaks out of outer loop instead of only the inner one
            }
          }
        }

        // For Each Loop
        // The for loop is also able to iterate over arrays as well as objects
        // that implement the Iterable interface.
        int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        // for each loop structure =&gt; for (&lt;object&gt; : &lt;iterable&gt;)
        // reads as: for each element in the iterable
        // note: the object type must match the element type of the iterable.
        for (int bar : fooList) {
            System.out.println(bar);
            //Iterates 9 times and prints 1-9 on new lines
        }

        // Switch Case
        // A switch works with the byte, short, char, and int data types.
        // It also works with enumerated types (discussed in Enum Types), the
        // String class, and a few special classes that wrap primitive types:
        // Character, Byte, Short, and Integer.
        // Starting in Java 7 and above, we can also use the String type.
        // Note: Do remember that, not adding "break" at end any particular case ends up in
        // executing the very next case(given it satisfies the condition provided) as well.
        int month = 3;
        String monthString;
        switch (month) {
            case 1: monthString = "January";
                    break;
            case 2: monthString = "February";
                    break;
            case 3: monthString = "March";
                    break;
            default: monthString = "Some other month";
                     break;
        }
        System.out.println("Switch Case Result: " + monthString);


        // Try-with-resources (Java 7+)
        // Try-catch-finally statements work as expected in Java but in Java 7+
        // the try-with-resources statement is also available. Try-with-resources
        // simplifies try-catch-finally statements by closing resources
        // automatically.

        // In order to use a try-with-resources, include an instance of a class
        // in the try statement. The class must implement java.lang.AutoCloseable.
        try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
            // You can attempt to do something that could throw an exception.
            System.out.println(br.readLine());
            // In Java 7, the resource will always be closed, even if it throws
            // an Exception.
        } catch (IOException | SQLException ex) {
            // Java 7+ Multi catch block handle both exceptions
        } catch (Exception ex) {
            //The resource will be closed before the catch statement executes.
            System.out.println("readLine() failed.");
        }
        // No need for a finally statement in this case, the BufferedReader is
        // already closed. This can be used to avoid certain edge cases where
        // a finally statement might not be called.
        // To learn more:
        // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


        // Conditional Shorthand
        // You can use the '?' operator for quick assignments or logic forks.
        // Reads as "If (statement) is true, use &lt;first value&gt;, otherwise, use
        // &lt;second value&gt;"
        int foo = 5;
        String bar = (foo &lt; 10) ? "A" : "B";
        System.out.println("bar : " + bar); // Prints "bar : A", because the
        // statement is true.
        // Or simply
        System.out.println("bar : " + (foo &lt; 10 ? "A" : "B"));


        ////////////////////////////////////////
        // Converting Data Types
        ////////////////////////////////////////

        // Converting data

        // Convert String To Integer
        Integer.parseInt("123");//returns an integer version of "123"

        // Convert Integer To String
        Integer.toString(123);//returns a string version of 123

        // For other conversions check out the following classes:
        // Double
        // Long
        // String

        ///////////////////////////////////////
        // Classes And Functions
        ///////////////////////////////////////

        System.out.println("\n-&gt;Classes &amp; Functions");

        // (definition of the Bicycle class follows)

        // Use new to instantiate a class
        Bicycle trek = new Bicycle();

        // Call object methods
        trek.speedUp(3); // You should always use setter and getter methods
        trek.setCadence(100);

        // toString returns this Object's string representation.
        System.out.println("trek info: " + trek.toString());
    } // End main method

    private static class TestInitialization {
        // Double Brace Initialization
        // Before Java 11, the Java Language had no syntax for how to create
        // static Collections in an easy way. Usually you end up like this:
        private static final Set&lt;String&gt; COUNTRIES = new HashSet&lt;String&gt;();
        static {
           COUNTRIES.add("DENMARK");
           COUNTRIES.add("SWEDEN");
           COUNTRIES.add("FINLAND");
        }

        // There's a nifty way to achieve the same thing, 
        // by using something that is called Double Brace Initialization.
        private static final Set&lt;String&gt; COUNTRIES_DOUBLE_BRACE = 
        new HashSet&lt;String&gt;() {{
            add("DENMARK");
            add("SWEDEN");
            add("FINLAND");
        }}

        // The first brace is creating a new AnonymousInnerClass and the
        // second one declares an instance initializer block. This block
        // is called when the anonymous inner class is created.
        // This does not only work for Collections, it works for all
        // non-final classes.


        // Another option was to initialize the Collection from an array,
        // using Arrays.asList() method:
        private static final List&lt;String&gt; COUNTRIES_AS_LIST = 
                        Arrays.asList("SWEDEN", "DENMARK", "NORWAY");
        // This has one catch: the list we get is internally backed by the array,
        // and since arrays can't change their size, the list backed by the array
        // is not resizeable, which means we can't add new elements to it: 
        public static void main(String[] args) {
            COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException!
            // However, we can replace elements by index, just like in array: 
            COUNTRIES.set(1, "FINLAND");
            System.out.println(COUNTRIES); // prints [SWEDEN, FINLAND, NORWAY]
        }
        // The resizing problem can be circumvented 
        // by creating another Collection from the List:
         private static final Set&lt;String&gt; COUNTRIES_SET = 
                new HashSet&lt;&gt;(Arrays.asList("SWEDEN", "DENMARK", "NORWAY"));
        // It's perfectly fine to add anything to the Set of COUNTRIES now. 
    } // End TestInitialization class

    private static class TestJava11Initialization {
        // Since Java 11, there is a convenient option to initialize Collections:
        // Set.of() and List.of() methods. 
        private static final Set&lt;String&gt; COUNTRIES = 
                Set.of("SWEDEN", "DENMARK", "NORWAY");
        // There is a massive catch, though: Lists and Sets initialized like this 
        // 1) are immutable 
        // 2) can't contain null elements (even check for null elements fails)!
        public static void main(String[] args) {
            COUNTRIES.add("FINLAND"); // throws UnsupportedOperationException
            COUNTRIES.remove("NORWAY"); // throws UnsupportedOperationException 
            COUNTRIES.contains(null); // throws NullPointerException
        }
        private static final Set&lt;String&gt; COUNTRIES_WITH_NULL = 
                    Set.of("SWEDEN", null, "NORWAY"); // throws NullPointerException

    } // End TestJava11Initialization class
} // End LearnJava class

// You can include other, non-public outer-level classes in a .java file,
// but it is not good practice. Instead split classes into separate files.

// Class Declaration Syntax:
// &lt;public/private/protected&gt; class &lt;class name&gt; {
//    // data fields, constructors, functions all inside.
//    // functions are called as methods in Java.
// }

class Bicycle {

    // Bicycle's Fields/Variables
    public int cadence; // Public: Can be accessed from anywhere
    private int speed;  // Private: Only accessible from within the class
    protected int gear; // Protected: Accessible from the class and subclasses
    String name; // default: Only accessible from within this package
    static String className; // Static class variable

    // Static block
    // Java has no implementation of static constructors, but
    // has a static block that can be used to initialize class variables
    // (static variables).
    // This block will be called when the class is loaded.
    static {
        className = "Bicycle";
    }

    // Constructors are a way of creating classes
    // This is a constructor
    public Bicycle() {
        // You can also call another constructor:
        // this(1, 50, 5, "Bontrager");
        gear = 1;
        cadence = 50;
        speed = 5;
        name = "Bontrager";
    }
    // This is a constructor that takes arguments
    public Bicycle(int startCadence, int startSpeed, int startGear,
        String name) {
        this.gear = startGear;
        this.cadence = startCadence;
        this.speed = startSpeed;
        this.name = name;
    }

    // Method Syntax:
    // &lt;public/private/protected&gt; &lt;return type&gt; &lt;function name&gt;(&lt;args&gt;)

    // Java classes often implement getters and setters for their fields

    // Method declaration syntax:
    // &lt;access modifier&gt; &lt;return type&gt; &lt;method name&gt;(&lt;args&gt;)
    public int getCadence() {
        return cadence;
    }

    // void methods require no return statement
    public void setCadence(int newValue) {
        cadence = newValue;
    }
    public void setGear(int newValue) {
        gear = newValue;
    }
    public void speedUp(int increment) {
        speed += increment;
    }
    public void slowDown(int decrement) {
        speed -= decrement;
    }
    public void setName(String newName) {
        name = newName;
    }
    public String getName() {
        return name;
    }

    //Method to display the attribute values of this Object.
    @Override // Inherited from the Object class.
    public String toString() {
        return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
            " name: " + name;
    }
} // end class Bicycle

// PennyFarthing is a subclass of Bicycle
class PennyFarthing extends Bicycle {
    // (Penny Farthings are those bicycles with the big front wheel.
    // They have no gears.)

    public PennyFarthing(int startCadence, int startSpeed) {
        // Call the parent constructor with super
        super(startCadence, startSpeed, 0, "PennyFarthing");
    }

    // You should mark a method you're overriding with an @annotation.
    // To learn more about what annotations are and their purpose check this
    // out: http://docs.oracle.com/javase/tutorial/java/annotations/
    @Override
    public void setGear(int gear) {
        this.gear = 0;
    }
}

// Object casting
// Since the PennyFarthing class is extending the Bicycle class, we can say
// a PennyFarthing is a Bicycle and write :
// Bicycle bicycle = new PennyFarthing();
// This is called object casting where an object is taken for another one. There
// are lots of details and deals with some more intermediate concepts here:
// https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

// Interfaces
// Interface declaration syntax
// &lt;access-level&gt; interface &lt;interface-name&gt; extends &lt;super-interfaces&gt; {
//     // Constants
//     // Method declarations
// }

// Example - Food:
public interface Edible {
    public void eat(); // Any class that implements this interface, must
                       // implement this method.
}

public interface Digestible {
    public void digest();
    // Since Java 8, interfaces can have default method.
    public default void defaultMethod() {
        System.out.println("Hi from default method ...");
    }
}

// We can now create a class that implements both of these interfaces.
public class Fruit implements Edible, Digestible {
    @Override
    public void eat() {
        // ...
    }

    @Override
    public void digest() {
        // ...
    }
}

// In Java, you can extend only one class, but you can implement many
// interfaces. For example:
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
    InterfaceTwo {
    @Override
    public void InterfaceOneMethod() {
    }

    @Override
    public void InterfaceTwoMethod() {
    }

}

// Abstract Classes

// Abstract Class declaration syntax
// &lt;access-level&gt; abstract class &lt;abstract-class-name&gt; extends
// &lt;super-abstract-classes&gt; {
//     // Constants and variables
//     // Method declarations
// }

// Abstract Classes cannot be instantiated.
// Abstract classes may define abstract methods.
// Abstract methods have no body and are marked abstract
// Non-abstract child classes must @Override all abstract methods
// from their super-classes.
// Abstract classes can be useful when combining repetitive logic
// with customised behavior, but as Abstract classes require
// inheritance, they violate "Composition over inheritance"
// so consider other approaches using composition.
// https://en.wikipedia.org/wiki/Composition_over_inheritance

public abstract class Animal
{
    private int age;

    public abstract void makeSound();

    // Method can have a body
    public void eat()
    {
        System.out.println("I am an animal and I am Eating.");
        // Note: We can access private variable here.
        age = 30;
    }

    public void printAge()
    {
        System.out.println(age);
    }

    // Abstract classes can have main method.
    public static void main(String[] args)
    {
        System.out.println("I am abstract");
    }
}

class Dog extends Animal
{
    // Note still have to override the abstract methods in the
    // abstract class.
    @Override
    public void makeSound()
    {
        System.out.println("Bark");
        // age = 30;    ==&gt; ERROR!    age is private to Animal
    }

    // NOTE: You will get an error if you used the
    // @Override annotation here, since java doesn't allow
    // overriding of static methods.
    // What is happening here is called METHOD HIDING.
    // Check out this SO post: http://stackoverflow.com/questions/16313649/
    public static void main(String[] args)
    {
        Dog pluto = new Dog();
        pluto.makeSound();
        pluto.eat();
        pluto.printAge();
    }
}

// Final Classes

// Final Class declaration syntax
// &lt;access-level&gt; final &lt;final-class-name&gt; {
//     // Constants and variables
//     // Method declarations
// }

// Final classes are classes that cannot be inherited from and are therefore a
// final child. In a way, final classes are the opposite of abstract classes
// because abstract classes must be extended, but final classes cannot be
// extended.
public final class SaberToothedCat extends Animal
{
    // Note still have to override the abstract methods in the
    // abstract class.
    @Override
    public void makeSound()
    {
        System.out.println("Roar");
    }
}

// Final Methods
public abstract class Mammal()
{
    // Final Method Syntax:
    // &lt;access modifier&gt; final &lt;return type&gt; &lt;function name&gt;(&lt;args&gt;)

    // Final methods, like, final classes cannot be overridden by a child
    // class, and are therefore the final implementation of the method.
    public final boolean isWarmBlooded()
    {
        return true;
    }
}

// Java Records are a concise way to define immutable data carrier classes, automatically
// generating boilerplate code like constructors, equals(), hashCode()and toString().
// This automatically creates an immutable class Person with fields name and age.
public record Person(String name, int age) {}
Person p = new Person("Alice", 30);

// Enum Type
//
// An enum type is a special data type that enables for a variable to be a set
// of predefined constants. The variable must be equal to one of the values
// that have been predefined for it. Because they are constants, the names of
// an enum type's fields are in uppercase letters. In the Java programming
// language, you define an enum type by using the enum keyword. For example,
// you would specify a days-of-the-week enum type as:
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

// We can use our enum Day like that:
public class EnumTest {
    // Variable Enum
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;
            case FRIDAY:
                System.out.println("Fridays are better.");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("Weekends are best.");
                break;
            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs(); // =&gt; Mondays are bad.
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs(); // =&gt; Midweek days are so-so.
    }
}

// Enum types are much more powerful than we show above.
// The enum body can include methods and other fields.
// You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

// Getting Started with Lambda Expressions
//
// New to Java version 8 are lambda expressions. Lambdas are more commonly found
// in functional programming languages, which means they are methods which can
// be created without belonging to a class, passed around as if it were itself
// an object, and executed on demand.
//
// Final note, lambdas must implement a functional interface. A functional
// interface is one which has only a single abstract method declared. It can
// have any number of default methods. Lambda expressions can be used as an
// instance of that functional interface. Any interface meeting the requirements
// is treated as a functional interface. You can read more about interfaces
// above.
//
import java.util.Map;
import java.util.HashMap;
import java.util.function.*;
import java.security.SecureRandom;

public class Lambdas {
    public static void main(String[] args) {
        // Lambda declaration syntax:
        // &lt;zero or more parameters&gt; -&gt; &lt;expression body or statement block&gt;

        // We will use this hashmap in our examples below.
        Map&lt;String, String&gt; planets = new HashMap&lt;&gt;();
            planets.put("Mercury", "87.969");
            planets.put("Venus", "224.7");
            planets.put("Earth", "365.2564");
            planets.put("Mars", "687");
            planets.put("Jupiter", "4,332.59");
            planets.put("Saturn", "10,759");
            planets.put("Uranus", "30,688.5");
            planets.put("Neptune", "60,182");

        // Lambda with zero parameters using the Supplier functional interface
        // from java.util.function.Supplier. The actual lambda expression is
        // what comes after numPlanets =.
        Supplier&lt;String&gt; numPlanets = () -&gt; Integer.toString(planets.size());
        System.out.format("Number of Planets: %s\n\n", numPlanets.get());

        // Lambda with one parameter and using the Consumer functional interface
        // from java.util.function.Consumer. This is because planets is a Map,
        // which implements both Collection and Iterable. The forEach used here,
        // found in Iterable, applies the lambda expression to each member of
        // the Collection. The default implementation of forEach behaves as if:
        /*
            for (T t : this)
                action.accept(t);
        */

        // The actual lambda expression is the parameter passed to forEach.
        planets.keySet().forEach((p) -&gt; System.out.format("%s\n", p));

        // If you are only passing a single argument, then the above can also be
        // written as (note absent parentheses around p):
        planets.keySet().forEach(p -&gt; System.out.format("%s\n", p));

        // Tracing the above, we see that planets is a HashMap, keySet() returns
        // a Set of its keys, forEach applies each element as the lambda
        // expression of: (parameter p) -&gt; System.out.format("%s\n", p). Each
        // time, the element is said to be "consumed" and the statement(s)
        // referred to in the lambda body is applied. Remember the lambda body
        // is what comes after the -&gt;.

        // The above without use of lambdas would look more traditionally like:
        for (String planet : planets.keySet()) {
            System.out.format("%s\n", planet);
        }

        // This example differs from the above in that a different forEach
        // implementation is used: the forEach found in the HashMap class
        // implementing the Map interface. This forEach accepts a BiConsumer,
        // which generically speaking is a fancy way of saying it handles
        // the Set of each Key -&gt; Value pairs. This default implementation
        // behaves as if:
        /*
            for (Map.Entry&lt;K, V&gt; entry : map.entrySet())
                action.accept(entry.getKey(), entry.getValue());
        */

        // The actual lambda expression is the parameter passed to forEach.
        String orbits = "%s orbits the Sun in %s Earth days.\n";
        planets.forEach((K, V) -&gt; System.out.format(orbits, K, V));

        // The above without use of lambdas would look more traditionally like:
        for (String planet : planets.keySet()) {
            System.out.format(orbits, planet, planets.get(planet));
        }

        // Or, if following more closely the specification provided by the
        // default implementation:
        for (Map.Entry&lt;String, String&gt; planet : planets.entrySet()) {
            System.out.format(orbits, planet.getKey(), planet.getValue());
        }

        // These examples cover only the very basic use of lambdas. It might not
        // seem like much or even very useful, but remember that a lambda can be
        // created as an object that can later be passed as parameters to other
        // methods.
    }
}
</code></pre>
<p>JavaScript:</p>
<pre><code class="lang-plaintext">// Single-line comments start with two slashes.
/* Multiline comments start with slash-star,
   and end with star-slash */

// Statements can be terminated by ;
doStuff();

// ... but they don't have to be, as semicolons are automatically inserted
// wherever there's a newline, except in certain cases.
doStuff()

// Because those cases can cause unexpected results, we'll keep on using
// semicolons in this guide.

///////////////////////////////////
// 1. Numbers, Strings and Operators

// JavaScript has one number type (which is a 64-bit IEEE 754 double).
// Doubles have a 52-bit mantissa, which is enough to store integers
// up to about 9✕10¹⁵ precisely.
3; // = 3
1.5; // = 1.5

// Some basic arithmetic works as you'd expect.
1 + 1; // = 2
0.1 + 0.2; // = 0.30000000000000004
8 - 1; // = 7
10 * 2; // = 20
35 / 5; // = 7

// Including uneven division.
5 / 2; // = 2.5

// And modulo division.
10 % 2; // = 0
30 % 4; // = 2
18.5 % 7; // = 4.5

// Bitwise operations also work; when you perform a bitwise operation your float
// is converted to a signed int *up to* 32 bits.
1 &lt;&lt; 2; // = 4

// Precedence is enforced with parentheses.
(1 + 3) * 2; // = 8

// There are three special not-a-real-number values:
Infinity; // result of e.g. 1/0
-Infinity; // result of e.g. -1/0
NaN; // result of e.g. 0/0, stands for 'Not a Number'

// There's also a boolean type.
true;
false;

// Strings are created with ' or ".
'abc';
"Hello, world";

// Negation uses the ! symbol
!true; // = false
!false; // = true

// Equality is ===
1 === 1; // = true
2 === 1; // = false

// Inequality is !==
1 !== 1; // = false
2 !== 1; // = true

// More comparisons
1 &lt; 10; // = true
1 &gt; 10; // = false
2 &lt;= 2; // = true
2 &gt;= 2; // = true

// Strings are concatenated with +
"Hello " + "world!"; // = "Hello world!"

// ... which works with more than just strings
"1, 2, " + 3; // = "1, 2, 3"
"Hello " + ["world", "!"]; // = "Hello world,!"

// ...which can result in some weird behaviour...
13 + !0; // 14
"13" + !0; // '13true'

// and are compared with &lt; and &gt;
"a" &lt; "b"; // = true

// Type coercion is performed for comparisons with double equals...
"5" == 5; // = true
null == undefined; // = true

// ...unless you use ===
"5" === 5; // = false
null === undefined; // = false

// You can access characters in a string with `charAt`
"This is a string".charAt(0);  // = 'T'

// ...or use `substring` to get larger pieces.
"Hello world".substring(0, 5); // = "Hello"

// `length` is a property, so don't use ().
"Hello".length; // = 5

// There's also `null` and `undefined`.
null;      // used to indicate a deliberate non-value
undefined; // used to indicate a value is not currently present (although
           // `undefined` is actually a value itself)

// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy.
// Note that 0 is falsy and "0" is truthy, even though 0 == "0".

///////////////////////////////////
// 2. Variables, Arrays and Objects

// Variables are declared with the `var` keyword. JavaScript is dynamically
// typed, so you don't need to specify type. Assignment uses a single `=`
// character.
var someVar = 5;

// If you leave the var keyword off, you won't get an error...
someOtherVar = 10;

// ...but your variable will be created in the global scope, not in the scope
// you defined it in.

// Variables declared without being assigned to are set to undefined.
var someThirdVar; // = undefined

// If you want to declare a couple of variables, then you could use a comma
// separator
var someFourthVar = 2, someFifthVar = 4;

// There's shorthand for performing math operations on variables:
someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now
someVar *= 10; // now someVar is 100

// and an even-shorter-hand for adding or subtracting 1
someVar++; // now someVar is 101
someVar--; // back to 100

// Arrays are ordered lists of values, of any type.
var myArray = ["Hello", 45, true];

// Their members can be accessed using the square-brackets subscript syntax.
// Array indices start at zero.
myArray[1]; // = 45

// Arrays are mutable and of variable length.
myArray.push("World");
myArray.length; // = 4

// Add/Modify at specific index
myArray[3] = "Hello";

// Add and remove element from front or back end of an array
myArray.unshift(3); // Add as the first element
someVar = myArray.shift(); // Remove first element and return it
myArray.push(3); // Add as the last element
someVar = myArray.pop(); // Remove last element and return it

// Join all elements of an array with semicolon
var myArray0 = [32,false,"js",12,56,90];
myArray0.join(";"); // = "32;false;js;12;56;90"

// Get subarray of elements from index 1 (include) to 4 (exclude)
myArray0.slice(1,4); // = [false,"js",12]

// Remove 4 elements starting from index 2, and insert there strings
// "hi","wr" and "ld"; return removed subarray
myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90]
// myArray0 === [32,false,"hi","wr","ld"]

// JavaScript's objects are equivalent to "dictionaries" or "maps" in other
// languages: an unordered collection of key-value pairs.
var myObj = {key1: "Hello", key2: "World"};

// Keys are strings, but quotes aren't required if they're a valid
// JavaScript identifier. Values can be any type.
var myObj = {myKey: "myValue", "my other key": 4};

// Object attributes can also be accessed using the subscript syntax,
myObj["my other key"]; // = 4

// ... or using the dot syntax, provided the key is a valid identifier.
myObj.myKey; // = "myValue"

// Objects are mutable; values can be changed and new keys added.
myObj.myThirdKey = true;

// If you try to access a value that's not yet set, you'll get undefined.
myObj.myFourthKey; // = undefined

///////////////////////////////////
// 3. Logic and Control Structures

// The `if` structure works as you'd expect.
var count = 1;
if (count == 3){
    // evaluated if count is 3
} else if (count == 4){
    // evaluated if count is 4
} else {
    // evaluated if it's not either 3 or 4
}

// As does `while`.
while (true){
    // An infinite loop!
}

// Do-while loops are like while loops, except they always run at least once.
var input;
do {
    input = getInput();
} while (!isValid(input));

// The `for` loop is the same as C and Java:
// initialization; continue condition; iteration.
for (var i = 0; i &lt; 5; i++){
    // will run 5 times
}

// Breaking out of labeled loops is similar to Java
outer:
for (var i = 0; i &lt; 10; i++) {
    for (var j = 0; j &lt; 10; j++) {
        if (i == 5 &amp;&amp; j ==5) {
            break outer;
            // breaks out of outer loop instead of only the inner one
        }
    }
}

// The for/in statement allows iteration over properties of an object.
var description = "";
var person = {fname:"Paul", lname:"Ken", age:18};
for (var x in person){
    description += person[x] + " ";
} // description = 'Paul Ken 18 '

// The for/of statement allows iteration over iterable objects (including the built-in String, 
// Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set, 
// and user-defined iterables).
var myPets = "";
var pets = ["cat", "dog", "hamster", "hedgehog"];
for (var pet of pets){
    myPets += pet + " ";
} // myPets = 'cat dog hamster hedgehog '

// &amp;&amp; is logical and, || is logical or
if (house.size == "big" &amp;&amp; house.colour == "blue"){
    house.contains = "bear";
}
if (colour == "red" || colour == "blue"){
    // colour is either red or blue
}

// &amp;&amp; and || "short circuit", which is useful for setting default values.
var name = otherName || "default";

// The `switch` statement checks for equality with `===`.
// Use 'break' after each case
// or the cases after the correct one will be executed too.
grade = 'B';
switch (grade) {
  case 'A':
    console.log("Great job");
    break;
  case 'B':
    console.log("OK job");
    break;
  case 'C':
    console.log("You can do better");
    break;
  default:
    console.log("Oy vey");
    break;
}


///////////////////////////////////
// 4. Functions, Scope and Closures

// JavaScript functions are declared with the `function` keyword.
function myFunction(thing){
    return thing.toUpperCase();
}
myFunction("foo"); // = "FOO"

// Note that the value to be returned must start on the same line as the
// `return` keyword, otherwise you'll always return `undefined` due to
// automatic semicolon insertion. Watch out for this when using Allman style.
function myFunction(){
    return // &lt;- semicolon automatically inserted here
    {thisIsAn: 'object literal'};
}
myFunction(); // = undefined

// JavaScript functions are first class objects, so they can be reassigned to
// different variable names and passed to other functions as arguments - for
// example, when supplying an event handler:
function myFunction(){
    // this code will be called in 5 seconds' time
}
setTimeout(myFunction, 5000);
// Note: setTimeout isn't part of the JS language, but is provided by browsers
// and Node.js.

// Another function provided by browsers is setInterval
function myFunction(){
    // this code will be called every 5 seconds
}
setInterval(myFunction, 5000);

// Function objects don't even have to be declared with a name - you can write
// an anonymous function definition directly into the arguments of another.
setTimeout(function(){
    // this code will be called in 5 seconds' time
}, 5000);

// JavaScript has function scope; functions get their own scope but other blocks
// do not.
if (true){
    var i = 5;
}
i; // = 5 - not undefined as you'd expect in a block-scoped language

// This has led to a common pattern of "immediately-executing anonymous
// functions", which prevent temporary variables from leaking into the global
// scope.
(function(){
    var temporary = 5;
    // We can access the global scope by assigning to the "global object", which
    // in a web browser is always `window`. The global object may have a
    // different name in non-browser environments such as Node.js.
    window.permanent = 10;
})();
temporary; // raises ReferenceError
permanent; // = 10

// One of JavaScript's most powerful features is closures. If a function is
// defined inside another function, the inner function has access to all the
// outer function's variables, even after the outer function exits.
function sayHelloInFiveSeconds(name){
    var prompt = "Hello, " + name + "!";
    // Inner functions are put in the local scope by default, as if they were
    // declared with `var`.
    function inner(){
        alert(prompt);
    }
    setTimeout(inner, 5000);
    // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will
    // exit immediately, and setTimeout will call inner afterwards. However,
    // because inner is "closed over" sayHelloInFiveSeconds, inner still has
    // access to the `prompt` variable when it is finally called.
}
sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s

///////////////////////////////////
// 5. More about Objects; Constructors and Prototypes

// Objects can contain functions.
var myObj = {
    myFunc: function(){
        return "Hello world!";
    }
};
myObj.myFunc(); // = "Hello world!"

// When functions attached to an object are called, they can access the object
// they're attached to using the `this` keyword.
myObj = {
    myString: "Hello world!",
    myFunc: function(){
        return this.myString;
    }
};
myObj.myFunc(); // = "Hello world!"

// What `this` is set to has to do with how the function is called, not where
// it's defined. So, our function doesn't work if it isn't called in the
// context of the object.
var myFunc = myObj.myFunc;
myFunc(); // = undefined

// Inversely, a function can be assigned to the object and gain access to it
// through `this`, even if it wasn't attached when it was defined.
var myOtherFunc = function(){
    return this.myString.toUpperCase();
};
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = "HELLO WORLD!"

// We can also specify a context for a function to execute in when we invoke it
// using `call` or `apply`.

var anotherFunc = function(s){
    return this.myString + s;
};
anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"

// The `apply` function is nearly identical, but takes an array for an argument
// list.

anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"

// This is useful when working with a function that accepts a sequence of
// arguments and you want to pass an array.

Math.min(42, 6, 27); // = 6
Math.min([42, 6, 27]); // = NaN (uh-oh!)
Math.min.apply(Math, [42, 6, 27]); // = 6

// But, `call` and `apply` are only temporary. When we want it to stick, we can
// use `bind`.

var boundFunc = anotherFunc.bind(myObj);
boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"

// `bind` can also be used to partially apply (curry) a function.

var product = function(a, b){ return a * b; };
var doubler = product.bind(this, 2);
doubler(8); // = 16

// When you call a function with the `new` keyword, a new object is created, and
// made available to the function via the `this` keyword. Functions designed to be
// called like that are called constructors.

var MyConstructor = function(){
    this.myNumber = 5;
};
myNewObj = new MyConstructor(); // = {myNumber: 5}
myNewObj.myNumber; // = 5

// Unlike most other popular object-oriented languages, JavaScript has no
// concept of 'instances' created from 'class' blueprints; instead, JavaScript
// combines instantiation and inheritance into a single concept: a 'prototype'.

// Every JavaScript object has a 'prototype'. When you go to access a property
// on an object that doesn't exist on the actual object, the interpreter will
// look at its prototype.

// Some JS implementations let you access an object's prototype on the magic
// property `__proto__`. While this is useful for explaining prototypes it's not
// part of the standard; we'll get to standard ways of using prototypes later.
var myObj = {
    myString: "Hello world!"
};
var myPrototype = {
    meaningOfLife: 42,
    myFunc: function(){
        return this.myString.toLowerCase();
    }
};

myObj.__proto__ = myPrototype;
myObj.meaningOfLife; // = 42

// This works for functions, too.
myObj.myFunc(); // = "hello world!"

// Of course, if your property isn't on your prototype, the prototype's
// prototype is searched, and so on.
myPrototype.__proto__ = {
    myBoolean: true
};
myObj.myBoolean; // = true

// There's no copying involved here; each object stores a reference to its
// prototype. This means we can alter the prototype and our changes will be
// reflected everywhere.
myPrototype.meaningOfLife = 43;
myObj.meaningOfLife; // = 43

// The for/in statement allows iteration over properties of an object,
// walking up the prototype chain until it sees a null prototype.
for (var x in myObj){
    console.log(myObj[x]);
}
///prints:
// Hello world!
// 43
// [Function: myFunc]
// true

// To only consider properties attached to the object itself
// and not its prototypes, use the `hasOwnProperty()` check.
for (var x in myObj){
    if (myObj.hasOwnProperty(x)){
        console.log(myObj[x]);
    }
}
///prints:
// Hello world!

// We mentioned that `__proto__` was non-standard, and there's no standard way to
// change the prototype of an existing object. However, there are two ways to
// create a new object with a given prototype.

// The first is Object.create, which is a recent addition to JS, and therefore
// not available in all implementations yet.
var myObj = Object.create(myPrototype);
myObj.meaningOfLife; // = 43

// The second way, which works anywhere, has to do with constructors.
// Constructors have a property called prototype. This is *not* the prototype of
// the constructor function itself; instead, it's the prototype that new objects
// are given when they're created with that constructor and the new keyword.
MyConstructor.prototype = {
    myNumber: 5,
    getMyNumber: function(){
        return this.myNumber;
    }
};
var myNewObj2 = new MyConstructor();
myNewObj2.getMyNumber(); // = 5
myNewObj2.myNumber = 6;
myNewObj2.getMyNumber(); // = 6

// Built-in types like strings and numbers also have constructors that create
// equivalent wrapper objects.
var myNumber = 12;
var myNumberObj = new Number(12);
myNumber == myNumberObj; // = true

// Except, they aren't exactly equivalent.
typeof myNumber; // = 'number'
typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0){
    // This code won't execute, because 0 is falsy.
}
if (new Number(0)){
   // This code will execute, because wrapped numbers are objects, and objects
   // are always truthy.
}

// However, the wrapper objects and the regular builtins share a prototype, so
// you can actually add functionality to a string, for instance.
String.prototype.firstCharacter = function(){
    return this.charAt(0);
};
"abc".firstCharacter(); // = "a"

// This fact is often used in "polyfilling", which is implementing newer
// features of JavaScript in an older subset of JavaScript, so that they can be
// used in older environments such as outdated browsers.

// For instance, we mentioned that Object.create isn't yet available in all
// implementations, but we can still use it with this polyfill:
if (Object.create === undefined){ // don't overwrite it if it exists
    Object.create = function(proto){
        // make a temporary constructor with the right prototype
        var Constructor = function(){};
        Constructor.prototype = proto;
        // then use it to create a new, appropriately-prototyped object
        return new Constructor();
    };
}

// ES6 Additions

// The "let" keyword allows you to define variables in a lexical scope, 
// as opposed to a function scope like the var keyword does.
let name = "Billy";

// Variables defined with let can be reassigned new values.
name = "William";

// The "const" keyword allows you to define a variable in a lexical scope
// like with let, but you cannot reassign the value once one has been assigned.

const pi = 3.14;

pi = 4.13; // You cannot do this.

// There is a new syntax for functions in ES6 known as "lambda syntax".
// This allows functions to be defined in a lexical scope like with variables
// defined by const and let. 

const isEven = (number) =&gt; {
    return number % 2 === 0;
};

isEven(7); // false

// The "equivalent" of this function in the traditional syntax would look like this:

function isEven(number) {
    return number % 2 === 0;
};

// I put the word "equivalent" in double quotes because a function defined
// using the lambda syntax cannot be called before the definition.
// The following is an example of invalid usage:

add(1, 8);

const add = (firstNumber, secondNumber) =&gt; {
    return firstNumber + secondNumber;
};
</code></pre>
<p>Kotlin:</p>
<pre><code class="lang-plaintext">// Single-line comments start with //
/*
Multi-line comments look like this.
*/

// The "package" keyword works in the same way as in Java.
package com.learnxinyminutes.kotlin

/*
The entry point to a Kotlin program is a function named "main".
The function is passed an array containing any command-line arguments.
Since Kotlin 1.3 the "main" function can also be defined without
any parameters.
*/
fun main(args: Array&lt;String&gt;) {
    /*
    Declaring variables is done using either "var" or "val".
    "val" declarations cannot be reassigned, whereas "vars" can.
    */
    val fooVal = 10 // we cannot later reassign fooVal to something else
    var fooVar = 10
    fooVar = 20 // fooVar can be reassigned

    /*
    In most cases, Kotlin can determine what the type of a variable is,
    so we don't have to explicitly specify it every time.
    We can explicitly declare the type of a variable like so:
    */
    val foo: Int = 7

    /*
    Strings can be represented in a similar way as in Java.
    Escaping is done with a backslash.
    */
    val fooString = "My String Is Here!"
    val barString = "Printing on a new line?\nNo Problem!"
    val bazString = "Do you want to add a tab?\tNo Problem!"
    println(fooString)
    println(barString)
    println(bazString)

    /*
    A raw string is delimited by a triple quote (""").
    Raw strings can contain newlines and any other characters.
    */
    val fooRawString = """
fun helloWorld(val name : String) {
   println("Hello, world!")
}
"""
    println(fooRawString)

    /*
    Strings can contain template expressions.
    A template expression starts with a dollar sign ($).
    */
    val fooTemplateString = "$fooString has ${fooString.length} characters"
    println(fooTemplateString) // =&gt; My String Is Here! has 18 characters

    /*
    For a variable to hold null it must be explicitly specified as nullable.
    A variable can be specified as nullable by appending a ? to its type.
    We can access a nullable variable by using the ?. operator.
    We can use the ?: operator to specify an alternative value to use
    if a variable is null.
    */
    var fooNullable: String? = "abc"
    println(fooNullable?.length) // =&gt; 3
    println(fooNullable?.length ?: -1) // =&gt; 3
    fooNullable = null
    println(fooNullable?.length) // =&gt; null
    println(fooNullable?.length ?: -1) // =&gt; -1

    /*
    Functions can be declared using the "fun" keyword.
    Function arguments are specified in brackets after the function name.
    Function arguments can optionally have a default value.
    The function return type, if required, is specified after the arguments.
    */
    fun hello(name: String = "world"): String {
        return "Hello, $name!"
    }
    println(hello("foo")) // =&gt; Hello, foo!
    println(hello(name = "bar")) // =&gt; Hello, bar!
    println(hello()) // =&gt; Hello, world!

    /*
    A function parameter may be marked with the "vararg" keyword
    to allow a variable number of arguments to be passed to the function.
    */
    fun varargExample(vararg names: Int) {
        println("Argument has ${names.size} elements")
    }
    varargExample() // =&gt; Argument has 0 elements
    varargExample(1) // =&gt; Argument has 1 elements
    varargExample(1, 2, 3) // =&gt; Argument has 3 elements

    /*
    When a function consists of a single expression then the curly brackets can
    be omitted. The body is specified after the = symbol.
    */
    fun odd(x: Int): Boolean = x % 2 == 1
    println(odd(6)) // =&gt; false
    println(odd(7)) // =&gt; true

    // If the return type can be inferred then we don't need to specify it.
    fun even(x: Int) = x % 2 == 0
    println(even(6)) // =&gt; true
    println(even(7)) // =&gt; false

    /*
    You can also use lambda functions, with the '-&gt;' operator seperating
    the parameters from the function body.
    */
    val fooLambda: (Int) -&gt; Int = {n -&gt; n + 1}
    println(fooLambda(1)) // =&gt; 2

    // Functions can take functions as arguments and return functions.
    fun not(f: (Int) -&gt; Boolean): (Int) -&gt; Boolean {
        return {n -&gt; !f.invoke(n)}
    }
    // Named functions can be specified as arguments using the :: operator.
    val notOdd = not(::odd)
    val notEven = not(::even)
    /*
    Lambda expressions can be specified as arguments.
    If it's the only argument parentheses can be omitted.
    */
    val notZero = not {n -&gt; n == 0}
    /*
    If a lambda has only one parameter
    then its declaration can be omitted (along with the -&gt;).
    The name of the single parameter will be "it".
    */
    val notPositive = not {it &gt; 0}
    for (i in 0..4) {
        println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}")
    }

    // The "class" keyword is used to declare classes.
    class ExampleClass(val x: Int) {
        fun memberFunction(y: Int): Int {
            return x + y
        }

        infix fun infixMemberFunction(y: Int): Int {
            return x * y
        }
    }
    /*
    To create a new instance we call the constructor.
    Note that Kotlin does not have a "new" keyword.
    */
    val fooExampleClass = ExampleClass(7)
    // Member functions can be called using dot notation.
    println(fooExampleClass.memberFunction(4)) // =&gt; 11
    /*
    If a function has been marked with the "infix" keyword then it can be
    called using infix notation.
    */
    println(fooExampleClass infixMemberFunction 4) // =&gt; 28

    /*
    Data classes are a concise way to create classes that just hold data.
    The "hashCode"/"equals" and "toString" methods are automatically generated.
    */
    data class DataClassExample (val x: Int, val y: Int, val z: Int)
    val fooData = DataClassExample(1, 2, 4)
    println(fooData) // =&gt; DataClassExample(x=1, y=2, z=4)

    // Data classes have a "copy" function.
    val fooCopy = fooData.copy(y = 100)
    println(fooCopy) // =&gt; DataClassExample(x=1, y=100, z=4)

    // Objects can be destructured into multiple variables.
    val (a, b, c) = fooCopy
    println("$a $b $c") // =&gt; 1 100 4

    // destructuring in "for" loop
    for ((a, b, c) in listOf(fooData)) {
        println("$a $b $c") // =&gt; 1 2 4
    }

    val mapData = mapOf("a" to 1, "b" to 2)
    // Map.Entry is destructurable as well
    for ((key, value) in mapData) {
        println("$key -&gt; $value")
    }

    // The "with" function is similar to the JavaScript "with" statement.
    data class MutableDataClassExample (var x: Int, var y: Int, var z: Int)
    val fooMutableData = MutableDataClassExample(7, 4, 9)
    with (fooMutableData) {
        x -= 2
        y += 2
        z--
    }
    println(fooMutableData) // =&gt; MutableDataClassExample(x=5, y=6, z=8)

    /*
    We can create a list using the "listOf" function.
    The list will be immutable - elements cannot be added or removed.
    */
    val fooList = listOf("a", "b", "c")
    println(fooList.size) // =&gt; 3
    println(fooList.first()) // =&gt; a
    println(fooList.last()) // =&gt; c
    // Elements of a list can be accessed by their index.
    println(fooList[1]) // =&gt; b

    // A mutable list can be created using the "mutableListOf" function.
    val fooMutableList = mutableListOf("a", "b", "c")
    fooMutableList.add("d")
    println(fooMutableList.last()) // =&gt; d
    println(fooMutableList.size) // =&gt; 4

    // We can create a set using the "setOf" function.
    val fooSet = setOf("a", "b", "c")
    println(fooSet.contains("a")) // =&gt; true
    println(fooSet.contains("z")) // =&gt; false

    // We can create a map using the "mapOf" function.
    val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9)
    // Map values can be accessed by their key.
    println(fooMap["a"]) // =&gt; 8

    /*
    Sequences represent lazily-evaluated collections.
    We can create a sequence using the "generateSequence" function.
    */
    val fooSequence = generateSequence(1, { it + 1 })
    val x = fooSequence.take(10).toList()
    println(x) // =&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    // An example of using a sequence to generate Fibonacci numbers:
    fun fibonacciSequence(): Sequence&lt;Long&gt; {
        var a = 0L
        var b = 1L

        fun next(): Long {
            val result = a + b
            a = b
            b = result
            return a
        }

        return generateSequence(::next)
    }
    val y = fibonacciSequence().take(10).toList()
    println(y) // =&gt; [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

    // Kotlin provides higher-order functions for working with collections.
    val z = (1..9).map {it * 3}
                  .filter {it &lt; 20}
                  .groupBy {it % 2 == 0}
                  .mapKeys {if (it.key) "even" else "odd"}
    println(z) // =&gt; {odd=[3, 9, 15], even=[6, 12, 18]}

    // A "for" loop can be used with anything that provides an iterator.
    for (c in "hello") {
        println(c)
    }

    // "while" loops work in the same way as other languages.
    var ctr = 0
    while (ctr &lt; 5) {
        println(ctr)
        ctr++
    }
    do {
        println(ctr)
        ctr++
    } while (ctr &lt; 10)

    /*
    "if" can be used as an expression that returns a value.
    For this reason the ternary ?: operator is not needed in Kotlin.
    */
    val num = 5
    val message = if (num % 2 == 0) "even" else "odd"
    println("$num is $message") // =&gt; 5 is odd

    // "when" can be used as an alternative to "if-else if" chains.
    val i = 10
    when {
        i &lt; 7 -&gt; println("first block")
        fooString.startsWith("hello") -&gt; println("second block")
        else -&gt; println("else block")
    }

    // "when" can be used with an argument.
    when (i) {
        0, 21 -&gt; println("0 or 21")
        in 1..20 -&gt; println("in the range 1 to 20")
        else -&gt; println("none of the above")
    }

    // "when" can be used as an expression that returns a value.
    var result = when (i) {
        0, 21 -&gt; "0 or 21"
        in 1..20 -&gt; "in the range 1 to 20"
        else -&gt; "none of the above"
    }
    println(result)

    /*
    We can check if an object is of a particular type by using the "is" operator.
    If an object passes a type check then it can be used as that type without
    explicitly casting it.
    */
    fun smartCastExample(x: Any) : Boolean {
        if (x is Boolean) {
            // x is automatically cast to Boolean
            return x
        } else if (x is Int) {
            // x is automatically cast to Int
            return x &gt; 0
        } else if (x is String) {
            // x is automatically cast to String
            return x.isNotEmpty()
        } else {
            return false
        }
    }
    println(smartCastExample("Hello, world!")) // =&gt; true
    println(smartCastExample("")) // =&gt; false
    println(smartCastExample(5)) // =&gt; true
    println(smartCastExample(0)) // =&gt; false
    println(smartCastExample(true)) // =&gt; true

    // Smartcast also works with when block
    fun smartCastWhenExample(x: Any) = when (x) {
        is Boolean -&gt; x
        is Int -&gt; x &gt; 0
        is String -&gt; x.isNotEmpty()
        else -&gt; false
    }

    /*
    Extensions are a way to add new functionality to a class.
    This is similar to C# extension methods.
    */
    fun String.remove(c: Char): String {
        return this.filter {it != c}
    }
    println("Hello, world!".remove('l')) // =&gt; Heo, word!
}

// Enum classes are similar to Java enum types.
enum class EnumExample {
    A, B, C // Enum constants are separated with commas.
}
fun printEnum() = println(EnumExample.A) // =&gt; A

// Since each enum is an instance of the enum class, they can be initialized as:
enum class EnumExample(val value: Int) {
    A(value = 1),
    B(value = 2),
    C(value = 3)
}
fun printProperty() = println(EnumExample.A.value) // =&gt; 1

// Every enum has properties to obtain its name and ordinal(position) in the enum class declaration:
fun printName() = println(EnumExample.A.name) // =&gt; A
fun printPosition() = println(EnumExample.A.ordinal) // =&gt; 0

/*
The "object" keyword can be used to create singleton objects.
We cannot instantiate it but we can refer to its unique instance by its name.
This is similar to Scala singleton objects.
*/
object ObjectExample {
    fun hello(): String {
        return "hello"
    }

    override fun toString(): String {
        return "Hello, it's me, ${ObjectExample::class.simpleName}"
    }
}


fun useSingletonObject() {
    println(ObjectExample.hello()) // =&gt; hello
    // In Kotlin, "Any" is the root of the class hierarchy, just like "Object" is in Java
    val someRef: Any = ObjectExample
    println(someRef) // =&gt; Hello, it's me, ObjectExample
}


/* The not-null assertion operator (!!) converts any value to a non-null type and
throws an exception if the value is null.
*/
var b: String? = "abc"
val l = b!!.length

data class Counter(var value: Int) {
    // overload Counter += Int
    operator fun plusAssign(increment: Int) {
        this.value += increment
    }

    // overload Counter++ and ++Counter
    operator fun inc() = Counter(value + 1)

    // overload Counter + Counter
    operator fun plus(other: Counter) = Counter(this.value + other.value)

    // overload Counter * Counter
    operator fun times(other: Counter) = Counter(this.value * other.value)

    // overload Counter * Int
    operator fun times(value: Int) = Counter(this.value * value)

    // overload Counter in Counter
    operator fun contains(other: Counter) = other.value == this.value

    // overload Counter[Int] = Int
    operator fun set(index: Int, value: Int) {
        this.value = index + value
    }

    // overload Counter instance invocation
    operator fun invoke() = println("The value of the counter is $value")

}
/* You can also overload operators through extension methods */
// overload -Counter
operator fun Counter.unaryMinus() = Counter(-this.value)

fun operatorOverloadingDemo() {
    var counter1 = Counter(0)
    var counter2 = Counter(5)
    counter1 += 7
    println(counter1) // =&gt; Counter(value=7)
    println(counter1 + counter2) // =&gt; Counter(value=12)
    println(counter1 * counter2) // =&gt; Counter(value=35)
    println(counter2 * 2) // =&gt; Counter(value=10)
    println(counter1 in Counter(5)) // =&gt; false
    println(counter1 in Counter(7)) // =&gt; true
    counter1[26] = 10
    println(counter1) // =&gt; Counter(value=36)
    counter1() // =&gt; The value of the counter is 36
    println(-counter2) // =&gt; Counter(value=-5)
}
</code></pre>
<p>Lua:</p>
<pre><code class="lang-plaintext">-- Two dashes start a one-line comment.

--[[
     Adding two ['s and ]'s makes it a
     multi-line comment.
--]]

----------------------------------------------------
-- 1. Variables and flow control.
----------------------------------------------------

num = 42  -- Numbers can be integer or floating point.

s = 'walternate'  -- Immutable strings like Python.
t = "double-quotes are also fine"
u = [[ Double brackets
       start and end
       multi-line strings.]]
t = nil  -- Undefines t; Lua has garbage collection.

-- Blocks are denoted with keywords like do/end:
while num &lt; 50 do
  num = num + 1  -- No ++ or += type operators.
end

-- If clauses:
if num &gt; 40 then
  print('over 40')
elseif s ~= 'walternate' then  -- ~= is not equals.
  -- Equality check is == like Python; ok for strs.
  io.write('not over 40\n')  -- Defaults to stdout.
else
  -- Variables are global by default.
  thisIsGlobal = 5  -- Camel case is common.

  -- How to make a variable local:
  local line = io.read()  -- Reads next stdin line.

  -- String concatenation uses the .. operator:
  print('Winter is coming, ' .. line)
end

-- Undefined variables return nil.
-- This is not an error:
foo = anUnknownVariable  -- Now foo = nil.

aBoolValue = false

-- Only nil and false are falsy; 0 and '' are true!
if not aBoolValue then print('it was false') end

-- 'or' and 'and' are short-circuited.
-- This is similar to the a?b:c operator in C/js:
ans = aBoolValue and 'yes' or 'no'  --&gt; 'no'

karlSum = 0
for i = 1, 100 do  -- The range includes both ends.
  karlSum = karlSum + i
end

-- Use "100, 1, -1" as the range to count down:
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end

-- In general, the range is begin, end[, step].

-- Another loop construct:
repeat
  print('the way of the future')
  num = num - 1
until num == 0


----------------------------------------------------
-- 2. Functions.
----------------------------------------------------

function fib(n)
  if n &lt; 2 then return 1 end
  return fib(n - 2) + fib(n - 1)
end

-- Closures and anonymous functions are ok:
function adder(x)
  -- The returned function is created when adder is
  -- called, and remembers the value of x:
  return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16))  --&gt; 25
print(a2(64))  --&gt; 100

-- Returns, func calls, and assignments all work
-- with lists that may be mismatched in length.
-- Unmatched receivers are nil;
-- unmatched senders are discarded.

x, y, z = 1, 2, 3, 4
-- Now x = 1, y = 2, z = 3, and 4 is thrown away.

function bar(a, b, c)
  print(a, b, c)
  return 4, 8, 15, 16, 23, 42
end

x, y = bar('zaphod')  --&gt; prints "zaphod  nil nil"
-- Now x = 4, y = 8, values 15...42 are discarded.

-- Functions are first-class, may be local/global.
-- These are the same:
function f(x) return x * x end
f = function (x) return x * x end

-- And so are these:
local function g(x) return math.sin(x) end
local g; g  = function (x) return math.sin(x) end
-- the 'local g' decl makes g-self-references ok.

-- Trig funcs work in radians, by the way.

-- Calls with one string param don't need parens:
print 'hello'  -- Works fine.


----------------------------------------------------
-- 3. Tables.
----------------------------------------------------

-- Tables = Lua's only compound data structure;
--          they are associative arrays.
-- Similar to php arrays or js objects, they are
-- hash-lookup dicts that can also be used as lists.

-- Using tables as dictionaries / maps:

-- Dict literals have string keys by default:
t = {key1 = 'value1', key2 = false}

-- String keys can use js-like dot notation:
print(t.key1)  -- Prints 'value1'.
t.newKey = {}  -- Adds a new key/value pair.
t.key2 = nil   -- Removes key2 from the table.

-- Literal notation for any (non-nil) value as key:
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28])  -- prints "tau"

-- Key matching is basically by value for numbers
-- and strings, but by identity for tables.
a = u['@!#']  -- Now a = 'qbert'.
b = u[{}]     -- We might expect 1729, but it's nil:
-- b = nil since the lookup fails. It fails
-- because the key we used is not the same object
-- as the one used to store the original value. So
-- strings &amp; numbers are more portable keys.

-- A one-table-param function call needs no parens:
function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'}  -- Prints 'Sonmi~451'.

for key, val in pairs(u) do  -- Table iteration.
  print(key, val)
end

-- _G is a special table of all globals.
print(_G['_G'] == _G)  -- Prints 'true'.

-- Using tables as lists / arrays:

-- List literals implicitly set up int keys:
v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do  -- #v is the size of v for lists.
  print(v[i])  -- Indices start at 1 !! SO CRAZY!
end
-- A 'list' is not a real type. v is just a table
-- with consecutive integer keys, treated as a list.

----------------------------------------------------
-- 3.1 Metatables and metamethods.
----------------------------------------------------

-- A table can have a metatable that gives the table
-- operator-overloadish behavior. Later we'll see
-- how metatables support js-prototype behavior.

f1 = {a = 1, b = 2}  -- Represents the fraction a/b.
f2 = {a = 2, b = 3}

-- This would fail:
-- s = f1 + f2

metafraction = {}
function metafraction.__add(f1, f2)
  sum = {}
  sum.b = f1.b * f2.b
  sum.a = f1.a * f2.b + f2.a * f1.b
  return sum
end

setmetatable(f1, metafraction)
setmetatable(f2, metafraction)

s = f1 + f2  -- call __add(f1, f2) on f1's metatable

-- f1, f2 have no key for their metatable, unlike
-- prototypes in js, so you must retrieve it as in
-- getmetatable(f1). The metatable is a normal table
-- with keys that Lua knows about, like __add.

-- But the next line fails since s has no metatable:
-- t = s + s
-- Class-like patterns given below would fix this.

-- An __index on a metatable overloads dot lookups:
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal  -- works! thanks, metatable

-- Direct table lookups that fail will retry using
-- the metatable's __index value, and this recurses.

-- An __index value can also be a function(tbl, key)
-- for more customized lookups.

-- Values of __index,add, .. are called metamethods.
-- Full list. Here a is a table with the metamethod.

-- __add(a, b)                     for a + b
-- __sub(a, b)                     for a - b
-- __mul(a, b)                     for a * b
-- __div(a, b)                     for a / b
-- __mod(a, b)                     for a % b
-- __pow(a, b)                     for a ^ b
-- __unm(a)                        for -a
-- __concat(a, b)                  for a .. b
-- __len(a)                        for #a
-- __eq(a, b)                      for a == b
-- __lt(a, b)                      for a &lt; b
-- __le(a, b)                      for a &lt;= b
-- __index(a, b)  &lt;fn or a table&gt;  for a.b
-- __newindex(a, b, c)             for a.b = c
-- __call(a, ...)                  for a(...)

----------------------------------------------------
-- 3.2 Class-like tables and inheritance.
----------------------------------------------------

-- Classes aren't built in; there are different ways
-- to make them using tables and metatables.

-- Explanation for this example is below it.

Dog = {}                                   -- 1.

function Dog:new()                         -- 2.
  newObj = {sound = 'woof'}                -- 3.
  self.__index = self                      -- 4.
  return setmetatable(newObj, self)        -- 5.
end

function Dog:makeSound()                   -- 6.
  print('I say ' .. self.sound)
end

mrDog = Dog:new()                          -- 7.
mrDog:makeSound()  -- 'I say woof'         -- 8.

-- 1. Dog acts like a class; it's really a table.
-- 2. function tablename:fn(...) is the same as
--    function tablename.fn(self, ...)
--    The : just adds a first arg called self.
--    Read 7 &amp; 8 below for how self gets its value.
-- 3. newObj will be an instance of class Dog.
-- 4. self = the class being instantiated. Often
--    self = Dog, but inheritance can change it.
--    newObj gets self's functions when we set both
--    newObj's metatable and self's __index to self.
-- 5. Reminder: setmetatable returns its first arg.
-- 6. The : works as in 2, but this time we expect
--    self to be an instance instead of a class.
-- 7. Same as Dog.new(Dog), so self = Dog in new().
-- 8. Same as mrDog.makeSound(mrDog); self = mrDog.

----------------------------------------------------

-- Inheritance example:

LoudDog = Dog:new()                           -- 1.

function LoudDog:makeSound()
  s = self.sound .. ' '                       -- 2.
  print(s .. s .. s)
end

seymour = LoudDog:new()                       -- 3.
seymour:makeSound()  -- 'woof woof woof'      -- 4.

-- 1. LoudDog gets Dog's methods and variables.
-- 2. self has a 'sound' key from new(), see 3.
-- 3. Same as LoudDog.new(LoudDog), and converted to
--    Dog.new(LoudDog) as LoudDog has no 'new' key,
--    but does have __index = Dog on its metatable.
--    Result: seymour's metatable is LoudDog, and
--    LoudDog.__index = LoudDog. So seymour.key will
--    = seymour.key, LoudDog.key, Dog.key, whichever
--    table is the first with the given key.
-- 4. The 'makeSound' key is found in LoudDog; this
--    is the same as LoudDog.makeSound(seymour).

-- If needed, a subclass's new() is like the base's:
function LoudDog:new()
  newObj = {}
  -- set up newObj
  self.__index = self
  return setmetatable(newObj, self)
end

----------------------------------------------------
-- 4. Modules.
----------------------------------------------------


--[[ I'm commenting out this section so the rest of
--   this script remains runnable.
-- Suppose the file mod.lua looks like this:
local M = {}

local function sayMyName()
  print('Hrunkner')
end

function M.sayHello()
  print('Why hello there')
  sayMyName()
end

return M

-- Another file can use mod.lua's functionality:
local mod = require('mod')  -- Run the file mod.lua.

-- require is the standard way to include modules.
-- require acts like:     (if not cached; see below)
local mod = (function ()
  &lt;contents of mod.lua&gt;
end)()
-- It's like mod.lua is a function body, so that
-- locals inside mod.lua are invisible outside it.

-- This works because mod here = M in mod.lua:
mod.sayHello() -- Prints: Why hello there Hrunkner

-- This is wrong; sayMyName only exists in mod.lua:
mod.sayMyName()  -- error

-- require's return values are cached so a file is
-- run at most once, even when require'd many times.

-- Suppose mod2.lua contains "print('Hi!')".
local a = require('mod2')  -- Prints Hi!
local b = require('mod2')  -- Doesn't print; a=b.

-- dofile is like require without caching:
dofile('mod2.lua')  --&gt; Hi!
dofile('mod2.lua')  --&gt; Hi! (runs it again)

-- loadfile loads a lua file but doesn't run it yet.
f = loadfile('mod2.lua')  -- Call f() to run it.

-- load is loadfile for strings.
-- (loadstring is deprecated, use load instead)
g = load('print(343)')  -- Returns a function.
g()  -- Prints out 343; nothing printed before now.

--]]
</code></pre>
<p>Objective-C:</p>
<pre><code class="lang-plaintext">// Single-line comments start with //

/*
Multi-line comments look like this
*/

// XCode supports pragma mark directive that improve jump bar readability
#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions'
#pragma mark - Navigation Functions // Same tag, now with a separator

// Imports the Foundation headers with #import
// Use &lt;&gt; to import global files (in general frameworks)
// Use "" to import local files (from project)
#import &lt;Foundation/Foundation.h&gt;
#import "MyClass.h"

// If you enable modules for iOS &gt;= 7.0 or OS X &gt;= 10.9 projects in
// Xcode 5 you can import frameworks like that:
@import Foundation;

// Your program's entry point is a function called
// main with an integer return type
int main (int argc, const char * argv[])
{
    // Create an autorelease pool to manage the memory into the program
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    // If using automatic reference counting (ARC), use @autoreleasepool instead:
    @autoreleasepool {

    // Use NSLog to print lines to the console
    NSLog(@"Hello World!"); // Print the string "Hello World!"

    ///////////////////////////////////////
    // Types &amp; Variables
    ///////////////////////////////////////

    // Primitive declarations
    int myPrimitive1  = 1;
    long myPrimitive2 = 234554664565;

    // Object declarations
    // Put the * in front of the variable names for strongly-typed object declarations
    MyClass *myObject1 = nil;  // Strong typing
    id       myObject2 = nil;  // Weak typing
    // %@ is an object
    // 'description' is a convention to display the value of the Objects
    NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints =&gt; "(null) and (null)"

    // String
    NSString *worldString = @"World";
    NSLog(@"Hello %@!", worldString); // prints =&gt; "Hello World!"
    // NSMutableString is a mutable version of the NSString object
    NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"];
    [mutableString appendString:@" World!"];
    NSLog(@"%@", mutableString); // prints =&gt; "Hello World!"

    // Character literals
    NSNumber *theLetterZNumber = @'Z';
    char theLetterZ            = [theLetterZNumber charValue]; // or 'Z'
    NSLog(@"%c", theLetterZ);

    // Integral literals
    NSNumber *fortyTwoNumber = @42;
    int fortyTwo             = [fortyTwoNumber intValue]; // or 42
    NSLog(@"%i", fortyTwo);

    NSNumber *fortyTwoUnsignedNumber = @42U;
    unsigned int fortyTwoUnsigned    = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42
    NSLog(@"%u", fortyTwoUnsigned);

    NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42];
    short fortyTwoShort           = [fortyTwoShortNumber shortValue]; // or 42
    NSLog(@"%hi", fortyTwoShort);

    NSNumber *fortyOneShortNumber   = [NSNumber numberWithShort:41];
    unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41
    NSLog(@"%u", fortyOneUnsigned);

    NSNumber *fortyTwoLongNumber = @42L;
    long fortyTwoLong            = [fortyTwoLongNumber longValue]; // or 42
    NSLog(@"%li", fortyTwoLong);

    NSNumber *fiftyThreeLongNumber   = @53L;
    unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // or 53
    NSLog(@"%lu", fiftyThreeUnsigned);

    // Floating point literals
    NSNumber *piFloatNumber = @3.141592654F;
    float piFloat           = [piFloatNumber floatValue]; // or 3.141592654f
    NSLog(@"%f", piFloat); // prints =&gt; 3.141592654
    NSLog(@"%5.2f", piFloat); // prints =&gt; " 3.14"

    NSNumber *piDoubleNumber = @3.1415926535;
    double piDouble          = [piDoubleNumber doubleValue]; // or 3.1415926535
    NSLog(@"%f", piDouble);
    NSLog(@"%4.2f", piDouble); // prints =&gt; "3.14"

    // NSDecimalNumber is a fixed-point class that's more precise than float or double
    NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"];
    NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"];
    // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own:
    [oneDecNum decimalNumberByAdding:twoDecNum];
    [oneDecNum decimalNumberBySubtracting:twoDecNum];
    [oneDecNum decimalNumberByMultiplyingBy:twoDecNum];
    [oneDecNum decimalNumberByDividingBy:twoDecNum];
    NSLog(@"%@", oneDecNum); // prints =&gt; 10.99 as NSDecimalNumber is immutable

    // BOOL literals
    NSNumber *yesNumber = @YES;
    NSNumber *noNumber  = @NO;
    // or
    BOOL yesBool = YES;
    BOOL noBool  = NO;
    NSLog(@"%i", yesBool); // prints =&gt; 1

    // Array object
    // May contain different data types, but must be an Objective-C object
    NSArray *anArray      = @[@1, @2, @3, @4];
    NSNumber *thirdNumber = anArray[2];
    NSLog(@"Third number = %@", thirdNumber); // prints =&gt; "Third number = 3"
    // Since Xcode 7, NSArray objects can be typed (Generics)
    NSArray&lt;NSString *&gt; *stringArray = @[@"hello", @"world"];
    // NSMutableArray is a mutable version of NSArray, allowing you to change
    // the items in the array and to extend or shrink the array object.
    // Convenient, but not as efficient as NSArray.
    NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2];
    [mutableArray addObject:@"Hello"];
    [mutableArray addObject:@"World"];
    [mutableArray removeObjectAtIndex:0];
    NSLog(@"%@", [mutableArray objectAtIndex:0]); // prints =&gt; "World"

    // Dictionary object
    NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" };
    NSObject *valueObject     = aDictionary[@"A Key"];
    NSLog(@"Object = %@", valueObject); // prints =&gt; "Object = (null)"
    // Since Xcode 7, NSDictionary objects can be typed (Generics)
    NSDictionary&lt;NSString *, NSNumber *&gt; *numberDictionary = @{@"a": @1, @"b": @2};
    // NSMutableDictionary also available as a mutable dictionary object
    NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2];
    [mutableDictionary setObject:@"value1" forKey:@"key1"];
    [mutableDictionary setObject:@"value2" forKey:@"key2"];
    [mutableDictionary removeObjectForKey:@"key1"];

    // Change types from Mutable To Immutable
    //In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable
    NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy];
    NSDictionary *mutableDictionaryChanged = [mutableDictionary copy];


    // Set object
    NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil];
    NSLog(@"%@", set); // prints =&gt; {(Hello, World)} (may be in different order)
    // Since Xcode 7, NSSet objects can be typed (Generics)
    NSSet&lt;NSString *&gt; *stringSet = [NSSet setWithObjects:@"hello", @"world", nil];
    // NSMutableSet also available as a mutable set object
    NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2];
    [mutableSet addObject:@"Hello"];
    [mutableSet addObject:@"Hello"];
    NSLog(@"%@", mutableSet); // prints =&gt; {(Hello)}

    ///////////////////////////////////////
    // Operators
    ///////////////////////////////////////

    // The operators works like in the C language
    // For example:
    2 + 5; // =&gt; 7
    4.2f + 5.1f; // =&gt; 9.3f
    3 == 2; // =&gt; 0 (NO)
    3 != 2; // =&gt; 1 (YES)
    1 &amp;&amp; 1; // =&gt; 1 (Logical and)
    0 || 1; // =&gt; 1 (Logical or)
    ~0x0F; // =&gt; 0xF0 (bitwise negation)
    0x0F &amp; 0xF0; // =&gt; 0x00 (bitwise AND)
    0x01 &lt;&lt; 1; // =&gt; 0x02 (bitwise left shift (by 1))

    ///////////////////////////////////////
    // Control Structures
    ///////////////////////////////////////

    // If-Else statement
    if (NO)
    {
        NSLog(@"I am never run");
    } else if (0)
    {
        NSLog(@"I am also never run");
    } else
    {
        NSLog(@"I print");
    }

    // Switch statement
    switch (2)
    {
        case 0:
        {
            NSLog(@"I am never run");
        } break;
        case 1:
        {
            NSLog(@"I am also never run");
        } break;
        default:
        {
            NSLog(@"I print");
        } break;
    }

    // While loops statements
    int ii = 0;
    while (ii &lt; 4)
    {
        NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value
    } // prints =&gt; "0,"
      //           "1,"
      //           "2,"
      //           "3,"

    // For loops statements
    int jj;
    for (jj=0; jj &lt; 4; jj++)
    {
        NSLog(@"%d,", jj);
    } // prints =&gt; "0,"
      //           "1,"
      //           "2,"
      //           "3,"

    // Foreach statements
    NSArray *values = @[@0, @1, @2, @3];
    for (NSNumber *value in values)
    {
        NSLog(@"%@,", value);
    } // prints =&gt; "0,"
      //           "1,"
      //           "2,"
      //           "3,"

    // Object for loop statement. Can be used with any Objective-C object type
    for (id item in values) {
        NSLog(@"%@,", item);
    } // prints =&gt; "0,"
      //           "1,"
      //           "2,"
      //           "3,"

    // Try-Catch-Finally statements
    @try
    {
        // Your statements here
        @throw [NSException exceptionWithName:@"FileNotFoundException"
                            reason:@"File Not Found on System" userInfo:nil];
    } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects.
    {
        NSLog(@"Exception: %@", e);
    } @finally
    {
        NSLog(@"Finally. Time to clean up.");
    } // prints =&gt; "Exception: File Not Found on System"
      //           "Finally. Time to clean up."

    // NSError objects are useful for function arguments to populate on user mistakes.
    NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil];

    ///////////////////////////////////////
    // Objects
    ///////////////////////////////////////

    // Create an object instance by allocating memory and initializing it
    // An object is not fully functional until both steps have been completed
    MyClass *myObject = [[MyClass alloc] init];

    // The Objective-C model of object-oriented programming is based on message
    // passing to object instances
    // In Objective-C one does not simply call a method; one sends a message
    [myObject instanceMethodWithParameter:@"Steve Jobs"];

    // Clean up the memory you used into your program
    [pool drain];

    // End of @autoreleasepool
    }

    // End the program
    return 0;
}

///////////////////////////////////////
// Classes And Functions
///////////////////////////////////////

// Declare your class in a header file (MyClass.h):
// Class declaration syntax:
// @interface ClassName : ParentClassName &lt;ImplementedProtocols&gt;
// {
//    type name; &lt;= variable declarations;
// }
// @property type name; &lt;= property declarations
// -/+ (type) Method declarations; &lt;= Method declarations
// @end
@interface MyClass : NSObject &lt;MyProtocol&gt; // NSObject is Objective-C's base object class.
{
    // Instance variable declarations (can exist in either interface or implementation file)
    int count; // Protected access by default.
    @private id data; // Private access (More convenient to declare in implementation file)
    NSString *name;
}
// Convenient notation for public access variables to auto generate a setter method
// By default, setter method name is 'set' followed by @property variable name
@property int propInt; // Setter method name = 'setPropInt'
@property (copy) id copyId; // (copy) =&gt; Copy the object during assignment
// (readonly) =&gt; Cannot set value outside @interface
@property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor
// You can customize the getter and setter names instead of using default 'set' name:
@property (getter=lengthGet, setter=lengthSet:) int length;

// Methods
+/- (return type)methodSignature:(Parameter Type *)parameterName;

// + for class methods:
+ (NSString *)classMethod;
+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight;

// - for instance methods:
- (NSString *)instanceMethodWithParameter:(NSString *)string;
- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number;

// Constructor methods with arguments:
- (id)initWithDistance:(int)defaultDistance;
// Objective-C method names are very descriptive. Always name methods according to their arguments

@end // States the end of the interface


// To access public variables from the implementation file, @property generates a setter method
// automatically. Method name is 'set' followed by @property variable name:
MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance
[myClass setCount:10];
NSLog(@"%d", [myClass count]); // prints =&gt; 10
// Or using the custom getter and setter method defined in @interface:
[myClass lengthSet:32];
NSLog(@"%i", [myClass lengthGet]); // prints =&gt; 32
// For convenience, you may use dot notation to set and access object instance variables:
myClass.count = 45;
NSLog(@"%i", myClass.count); // prints =&gt; 45

// Call class methods:
NSString *classMethodString = [MyClass classMethod];
MyClass *classFromName = [MyClass myClassFromName:@"Hello"];

// Call instance methods:
MyClass *myClass = [[MyClass alloc] init]; // Create MyClass object instance
NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"];

// Selectors
// Way to dynamically represent methods. Used to call methods of a class, pass methods
// through functions to tell other classes they should call it, and to save methods
// as a variable
// SEL is the data type. @selector() returns a selector from method name provided
// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass
SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:);
if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method
    // Must put all method arguments into one object to send to performSelector function
    NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil];
    [myClass performSelector:selectorVar withObject:arguments]; // Calls the method
} else {
    // NSStringFromSelector() returns a NSString of the method name of a given selector
    NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar));
}

// Implement the methods in an implementation (MyClass.m) file:
@implementation MyClass {
    long distance; // Private access instance variable
    NSNumber *height;
}

// To access a public variable from the interface file, use '_' followed by variable name:
_count = 5; // References "int count" from MyClass interface
// Access variables defined in implementation file:
distance = 18; // References "long distance" from MyClass implementation
// To use @property variable in implementation, use @synthesize to create accessor variable:
@synthesize roString = _roString; // _roString available now in @implementation

// Called before calling any class methods or instantiating any objects
+ (void)initialize
{
    if (self == [MyClass class]) {
        distance = 0;
    }
}

// Counterpart to initialize method. Called when an object's reference count is zero
- (void)dealloc
{
    [height release]; // If not using ARC, make sure to release class variable objects
    [super dealloc];  // and call parent class dealloc
}

// Constructors are a way of creating instances of a class
// This is a default constructor which is called when the object is initialized.
- (id)init
{
    if ((self = [super init])) // 'super' used to access methods from parent class
    {
        self.count = 1; // 'self' used for object to call itself
    }
    return self;
}
// Can create constructors that contain arguments:
- (id)initWithDistance:(int)defaultDistance
{
    distance = defaultDistance;
    return self;
}

+ (NSString *)classMethod
{
    return @"Some string";
}

+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight
{
    height = defaultHeight;
    return [[self alloc] init];
}

- (NSString *)instanceMethodWithParameter:(NSString *)string
{
    return @"New string";
}

- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number
{
    return @42;
}

// Objective-C does not have private method declarations, but you can simulate them.
// To simulate a private method, create the method in the @implementation but not in the @interface.
- (NSNumber *)secretPrivateMethod {
    return @72;
}
[self secretPrivateMethod]; // Calls private method

// Methods declared into MyProtocol
- (void)myProtocolMethod
{
    // statements
}

@end // States the end of the implementation

///////////////////////////////////////
// Categories
///////////////////////////////////////
// A category is a group of methods designed to extend a class. They allow you to add new methods
// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
// functionality to an object.
// Categories allow you to:
// -- Add methods to an existing class for organizational purposes.
// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods.
// -- Add ability to create protected and private methods to classes.
// NOTE: Do not override methods of the base class in a category even though you have the ability
// to. Overriding methods may cause compiler errors later between different categories and it
// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods.

// Here is a simple Car base class.
@interface Car : NSObject

@property NSString *make;
@property NSString *color;

- (void)turnOn;
- (void)accelerate;

@end

// And the simple Car base class implementation:
#import "Car.h"

@implementation Car

@synthesize make = _make;
@synthesize color = _color;

- (void)turnOn {
    NSLog(@"Car is on.");
}
- (void)accelerate {
    NSLog(@"Accelerating.");
}

@end

// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would
// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
// functionality to this existing Car. A good example would be to clean the car. So we would create
// a category to add these cleaning methods:
// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)
#import "Car.h" // Make sure to import base class to extend.

@interface Car (Clean) // The category name is inside () following the name of the base class.

- (void)washWindows; // Names of the new methods we are adding to our Car object.
- (void)wax;

@end

// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m)
#import "Car+Clean.h" // Import the Clean category's @interface file.

@implementation Car (Clean)

- (void)washWindows {
    NSLog(@"Windows washed.");
}
- (void)wax {
    NSLog(@"Waxed.");
}

@end

// Any Car object instance has the ability to use a category. All they need to do is import it:
#import "Car+Clean.h" // Import as many different categories as you want to use.
#import "Car.h" // Also need to import base class to use it's original functionality.

int main (int argc, const char * argv[]) {
    @autoreleasepool {
        Car *mustang = [[Car alloc] init];
        mustang.color = @"Red";
        mustang.make = @"Ford";

        [mustang turnOn]; // Use methods from base Car class.
        [mustang washWindows]; // Use methods from Car's Clean category.
    }
    return 0;
}

// Objective-C does not have protected method declarations but you can simulate them.
// Create a category containing all of the protected methods, then import it ONLY into the
// @implementation file of a class belonging to the Car class:
@interface Car (Protected) // Naming category 'Protected' to remember methods are protected.

- (void)lockCar; // Methods listed here may only be created by Car objects.

@end
//To use protected methods, import the category, then implement the methods:
#import "Car+Protected.h" // Remember, import in the @implementation file only.

@implementation Car

- (void)lockCar {
    NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface.
}

@end

///////////////////////////////////////
// Extensions
///////////////////////////////////////
// Extensions allow you to override public access property attributes and methods of an @interface.
// @interface filename: Shape.h
@interface Shape : NSObject // Base Shape class extension overrides below.

@property (readonly) NSNumber *numOfSides;

- (int)getNumOfSides;

@end
// You can override numOfSides variable or getNumOfSides method to edit them with an extension:
// @implementation filename: Shape.m
#import "Shape.h"
// Extensions live in the same file as the class @implementation.
@interface Shape () // () after base class name declares an extension.

@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly.
-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int.
-(void)privateMethod; // You can also create new private methods inside of extensions.

@end
// The main @implementation:
@implementation Shape

@synthesize numOfSides = _numOfSides;

-(NSNumber)getNumOfSides { // All statements inside of extension must be in the @implementation.
    return _numOfSides;
}
-(void)privateMethod {
    NSLog(@"Private method created by extension. Shape instances cannot call me.");
}

@end

// Starting in Xcode 7.0, you can create Generic classes,
// allowing you to provide greater type safety and clarity
// without writing excessive boilerplate.
@interface Result&lt;__covariant A&gt; : NSObject

- (void)handleSuccess:(void(^)(A))success
              failure:(void(^)(NSError *))failure;

@property (nonatomic) A object;

@end

// we can now declare instances of this class like
Result&lt;NSNumber *&gt; *result;
Result&lt;NSArray *&gt; *result;

// Each of these cases would be equivalent to rewriting Result's interface
// and substituting the appropriate type for A
@interface Result : NSObject
- (void)handleSuccess:(void(^)(NSArray *))success
              failure:(void(^)(NSError *))failure;
@property (nonatomic) NSArray * object;
@end

@interface Result : NSObject
- (void)handleSuccess:(void(^)(NSNumber *))success
              failure:(void(^)(NSError *))failure;
@property (nonatomic) NSNumber * object;
@end

// It should be obvious, however, that writing one
//  Class to solve a problem is always preferable to writing two

// Note that Clang will not accept generic types in @implementations,
// so your @implemnation of Result would have to look like this:

@implementation Result

- (void)handleSuccess:(void (^)(id))success
              failure:(void (^)(NSError *))failure {
  // Do something
}

@end


///////////////////////////////////////
// Protocols
///////////////////////////////////////
// A protocol declares methods that can be implemented by any class.
// Protocols are not classes themselves. They simply define an interface
// that other objects are responsible for implementing.
// @protocol filename: "CarUtilities.h"
@protocol CarUtilities &lt;NSObject&gt; // &lt;NSObject&gt; =&gt; Name of another protocol this protocol includes.
    @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and
    - (void)turnOnEngine; // all defined methods.
@end
// Below is an example class implementing the protocol.
#import "CarUtilities.h" // Import the @protocol file.

@interface Car : NSObject &lt;CarUtilities&gt; // Name of protocol goes inside &lt;&gt;
    // You don't need the @property or method names here for CarUtilities. Only @implementation does.
- (void)turnOnEngineWithUtilities:(id &lt;CarUtilities&gt;)car; // You can use protocols as data too.
@end
// The @implementation needs to implement the @properties and methods for the protocol.
@implementation Car : NSObject &lt;CarUtilities&gt;

@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property.

- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define
    _engineOn = YES; // how you implement a method, it just requires that you do implement it.
}
// You may use a protocol as data as you know what methods and variables it has implemented.
- (void)turnOnEngineWithCarUtilities:(id &lt;CarUtilities&gt;)objectOfSomeKind {
    [objectOfSomeKind engineOn]; // You have access to object variables
    [objectOfSomeKind turnOnEngine]; // and the methods inside.
    [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants.
}

@end
// Instances of Car now have access to the protocol.
Car *carInstance = [[Car alloc] init];
[carInstance setEngineOn:NO];
[carInstance turnOnEngine];
if ([carInstance engineOn]) {
    NSLog(@"Car engine is on."); // prints =&gt; "Car engine is on."
}
// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods:
if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
    NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol.");
} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) {
    NSLog(@"This does run as the Car class implements the CarUtilities protocol.");
}
// Categories may implement protocols as well: @interface Car (CarCategory) &lt;CarUtilities&gt;
// You may implement many protocols: @interface Car : NSObject &lt;CarUtilities, CarCleaning&gt;
// NOTE: If two or more protocols rely on each other, make sure to forward-declare them:
#import "Brother.h"

@protocol Brother; // Forward-declare statement. Without it, compiler will throw error.

@protocol Sister &lt;NSObject&gt;

- (void)beNiceToBrother:(id &lt;Brother&gt;)brother;

@end

// See the problem is that Sister relies on Brother, and Brother relies on Sister.
#import "Sister.h"

@protocol Sister; // These lines stop the recursion, resolving the issue.

@protocol Brother &lt;NSObject&gt;

- (void)beNiceToSister:(id &lt;Sister&gt;)sister;

@end


///////////////////////////////////////
// Blocks
///////////////////////////////////////
// Blocks are statements of code, just like a function, that are able to be used as data.
// Below is a simple block with an integer argument that returns the argument plus 4.
^(int n) {
    return n + 4;
}
int (^addUp)(int n); // Declare a variable to store a block.
void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments.
// Blocks have access to variables in the same scope. But the variables are readonly and the
// value passed to the block is the value of the variable when the block is created.
int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17.
__block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar.
addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters.
    NSLog(@"You may have as many lines in a block as you would like.");
    NSSet *blockSet; // Also, you can declare local variables.
    mutableVar = 32; // Assigning new value to __block variable.
    return n + outsideVar; // Return statements are optional.
}
int addUp = addUp(10 + 16); // Calls block code with arguments.
// Blocks are often used as arguments to functions to be called later, or for callbacks.
@implementation BlockExample : NSObject

 - (void)runBlock:(void (^)(NSString))block {
    NSLog(@"Block argument returns nothing and takes in a NSString object.");
    block(@"Argument given to block to execute."); // Calling block.
 }

 @end


///////////////////////////////////////
// Memory Management
///////////////////////////////////////
/*
For each object used in an application, memory must be allocated for that object. When the application
is done using that object, memory must be deallocated to ensure application efficiency.
Objective-C does not use garbage collection and instead uses reference counting. As long as
there is at least one reference to an object (also called "owning" an object), then the object
will be available to use (known as "ownership").

When an instance owns an object, its reference counter is increments by one. When the
object is released, the reference counter decrements by one. When reference count is zero,
the object is removed from memory.

With all object interactions, follow the pattern of:
(1) create the object, (2) use the object, (3) then free the object from memory.
*/

MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object
[classVar release]; // Decrements classVar's reference count
// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to object
MyClass *newVar = [classVar retain]; // If classVar is released, object is still in memory because newVar is owner
[classVar autorelease]; // Removes ownership of object at end of @autoreleasepool block. Returns pointer to object

// @property can use 'retain' and 'assign' as well for small convenient definitions
@property (retain) MyClass *instance; // Release old value and retain a new one (strong reference)
@property (assign) NSSet *set; // Pointer to new value without retaining/releasing old (weak reference)

// Automatic Reference Counting (ARC)
// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC).
// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,
// you must not use retain, release, or autorelease
MyClass *arcMyClass = [[MyClass alloc] init];
// ... code using arcMyClass
// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,
// there is no need. It will insert this release statement for you

// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'
@property (weak) MyClass *weakVar; // 'weak' does not take ownership of object. If original instance's reference count
// is set to zero, weakVar will automatically receive value of nil to avoid application crashing
@property (strong) MyClass *strongVar; // 'strong' takes ownership of object. Ensures object will stay in memory to use

// For regular variables (not @property declared variables), use the following:
__strong NSString *strongString; // Default. Variable is retained in memory until it leaves it's scope
__weak NSSet *weakSet; // Weak reference to existing object. When existing object is released, weakSet is set to nil
__unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not set to nil when existing object is released
</code></pre>
<p>Stop Update.</p>
]]></content:encoded></item><item><title><![CDATA[List of Programming Language Syntax Designs Not Referred to at this Time]]></title><description><![CDATA[From Learn X in Y Minutes: Scenic Programming Language Tours
Ada:
--  Comments are written with a double hyphen and exist until the end of
--  the line.

--  You do not need to call the entry point "Main" or "main," you should
--  name it based on wh...]]></description><link>https://blog.axa6.com/list-of-programming-language-syntax-designs-not-referred-to-at-this-time</link><guid isPermaLink="true">https://blog.axa6.com/list-of-programming-language-syntax-designs-not-referred-to-at-this-time</guid><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Thu, 20 Mar 2025 12:12:22 GMT</pubDate><content:encoded><![CDATA[<p>From <a target="_blank" href="https://learnxinyminutes.com/">Learn X in Y Minutes: Scenic Programming Language Tours</a></p>
<p>Ada:</p>
<pre><code class="lang-plaintext">--  Comments are written with a double hyphen and exist until the end of
--  the line.

--  You do not need to call the entry point "Main" or "main," you should
--  name it based on what the program does.
procedure Empty is
   --  This is a declarative part.
begin
   --  Statements go here.
   null;  --  Do nothing here.
end Empty;

--  Ada compilers accept compilation units which can be library packages,
--  tasks, sub-programs, generics, etc.

--  This is where "context clauses" go, these can be pragmas or "with"
--  statements. "with" is equivalent to "include" or "import" in other
--  languages.
with Ada.Text_IO;  --  Get access to a library package.

procedure Hello is
begin
   Ada.Text_IO.Put_Line ("Hello, world");

   Ada.Text_IO.Put ("Hello again, world");
   Ada.Text_IO.New_Line;
end Hello;


--  Ada has a real module system. Modules are called packages and are split into
--  two component parts, the specification and a body.
--  It is important to introduce packages early, as you will be using them from
--  the start.
package Stuff is
   --  We could add the following line in order to tell the compiler that this
   --  package does not have to run any code before the "main" procedure starts.
   --  pragma Preelaborate;

   --  Packages can be nested within the same file or externally.
   --  Nested packages are accessed via dot notation, e.g. Stuff.Things.My.
   package Things is
      My : constant Integer := 100;
   end Things;

   --  If there are sub-programs declared within the specification, the body
   --  of the sub-program must be declared within the package body.
   procedure Do_Something;  --  If a subprogram takes no parameters, empty
                            --  parentheses are not required, unlike other
                            --  languages.

   --  We can also make generic sub-programs.
   generic
      type Element is (&lt;&gt;);  --  The "(&lt;&gt;)" notation specifies that only
                             --  discrete types can be passed into the generic.
   procedure Swap (Left, Right : in out Element);

   --  Sometimes we want to hide how a type is defined from the outside world
   --  so that nobody can mess with it directly. The full type must be defined
   --  within the private section below.
   type Blobs is private;

   --  We can also make types "limited" by putting this keyword after the "is"
   --  keyword, this means that the user cannot copy objects of that type
   --  around, like they normally could.
private
   type Blobs is new Integer range -25 .. 25;
end Stuff;


package body Stuff is
   --  Sub-program body.
   procedure Do_Something is
      --  We can nest sub-programs too.
      --  Parameters are defined with the direction of travel, in, in out, out.
      --  If the direction of travel is not specified, they are in by default.
      function Times_4 (Value : in Integer) return Integer is
      begin
         return Value * 4;
      end Times_4;

      I : Integer := 4;
   begin
      I := Times_4 (I);
   end Do_Something;


   --  Generic procedure body.
   procedure Swap (Left, Right : in out Element) is
      Temp : Element := Left;
   begin
      Left  := Right;
      Right := Temp;
   end Swap;
begin
   --  If we need to initialise something within the package, we can do it
   --  here.
   Do_Something;
end Stuff;


with Ada.Unchecked_Conversion;
with Ada.Text_IO;
with Stuff;

procedure LearnAdaInY is
   --  Indentation is 3 spaces.

   --  The most important feature in Ada is the type. Objects have types and an
   --  object of one type cannot be assigned to an object of another type.

   --  You can, and should, define your own types for the domain you are
   --  modelling. But you can use the standard types to start with and then
   --  replace them later with your own types, this could be called a form of
   --  gradual typing.

   --  The standard types would only really be a good starting point for binding
   --  to other languages, like C. Ada is the only language with a standardised
   --  way to bind with C, Fortran and COBOL! See the links in the References
   --  section with more information on binding to these languages.

   type Degrees is range 0 .. 360;  --  This is a type. Its underlying
                                    --  representation is an Integer.

   type Hues is (Red, Green, Blue, Purple, Yellow);  --  So is this. Here, we
                                                     --  are declaring an
                                                     --  Enumeration.

   --  This is a modular type. They behave like Integers that automatically
   --  wrap around. In this specific case, the range would be 0 .. 359.
   --  If we added 1 to a variable containing the value 359, we would receive
   --  back 0. They are very useful for arrays.
   type Degrees_Wrap is mod 360;

   --  You can restrict a type's range using a subtype, this makes them
   --  compatible with each other, i.e. the subtype can be assigned to an
   --  object of the type, as can be seen below.
   subtype Primaries is Hues range Red .. Blue;  --  This is a range.

   --  You can define variables or constants like this:
   --  Var_Name : Type := Value;

   --  10 is a universal integer. These universal numerics can be used with
   --  any type which matches the base type.
   Angle : Degrees := 10;
   Value : Integer := 20;
   --  New_Angle : Degrees := Value;  --  Incompatible types won't compile.
   --  New_Value : Integer := Angle;

   Blue_Hue   :          Primaries := Blue;  --  A variable.
   Red_Hue    : constant Primaries := Red;   --  A constant.
   Yellow_Hue : constant Hues      := Yellow;
   Colour_1   : constant Hues      := Red_Hue;
   --  Colour_2   : constant Primaries := Yellow_Hue;  --  uncomment to compile.

   --  You can force conversions, but then you are warned by the name of the
   --  package that you may be doing something unsafe.
   function Degrees_To_Int is new Ada.Unchecked_Conversion
     (Source =&gt; Degrees,   --  Line continuations are indented by 2 spaces.
      Target =&gt; Integer);

   New_Value_2 : Integer := Degrees_To_Int (Angle);  --  Note, space before (.

   --  GNAT is the GNU Ada Translator (compiler).
   --  Ada has a style guide and GNAT will warn you to adhere to it, and has
   --  option to check your style so that you can correct it so that all Ada
   --  source looks consistent. However, the style can be customized.

   --  Yes, you can even define your own floating and fixed point types, this
   --  is a very rare and unique ability. "digits" refers to the minimum
   --  digit precision that the type should support. "delta" is for fixed
   --  point types and refers to the smallest change that the type will support.
   type Real_Angles is digits 3 range 0.0 .. 360.0;
   type Fixed_Angles is delta 0.01 digits 5 range 0.0 .. 360.0;

   RA : constant Real_Angles  := 36.45;
   FA : constant Fixed_Angles := 360.0;  --  ".0" in order to make it a Float.

   --  You can have normal Latin 1 based strings by default.
   Str  : constant String    := "This is a constant string";
   --  When initialising from a string literal, the compiler knows the bounds,
   --  so we don't have to define them.

   --  Strings are arrays. Note how parentheses are used to access elements of
   --  an array? This is mathematical notation and was used because square
   --  brackets were not available on all keyboards at the time Ada was
   --  created. Also, because an array can be seen as a function from a
   --  mathematical perspective, so it made converting between arrays and
   --  functions easier.
   Char : constant Character := Str (Str'First);  --  "'First" is a type
                                                  --  attribute.

   --  Ada 2022 includes the use of [] for array initialisation when using
   --  containers, which were added in Ada 2012.

   --  Arrays are usually always defined as a type.
   --  They can be any dimension.
   type My_Array_1 is array (1 .. 4, 3 .. 7, -20 .. 20) of Integer;

   --  Yes, unlike other languages, you can index arrays with other discrete
   --  types such as enumerations and modular types or arbitrary ranges.
   type Axes is (X, Y, Z);

   --  You can define the array's range using the 'Range attribute from
   --  another type.
   type Vector is array (Axes'Range) of Float;

   V1 : constant Vector := (0.0, 0.0, 1.0);

   --  A record is the same as a structure in C, C++.
   type Entities is record
      Name     : String (1 .. 10);  --  Always starts at a positive value,
                                    --  inclusive range.
      Position : Vector;
   end record;

   --  In Ada, array bounds are immutable. You therefore have to provide a
   --  string literal with a value for every character.
   E1 : constant Entities := ("Blob      ", (0.0, 0.0, 0.0));

   --  An alternative is to use an array aggregate and assign a default value
   --  to every element that wasn't previously assigned in this aggregate.
   --  "others" is used to indicate anything else that has not been
   --  explicitly initialized.
   E2 : constant Entities := (('B', 'l', 'o', 'b', others =&gt; ' '),
                              (0.0, 0.0, 0.0));

   --  There are dynamic length strings (see references section) available in
   --  the standard library.

   --  We can make an object be initialised to its default values with the box
   --  notation, "&lt;&gt;". "others" is used to indicate anything else that has not
   --  been explicitly initialized.
   Null_Entity : constant Entities := (others =&gt; &lt;&gt;);

   --  Object-orientation is accomplished via an extension of record syntax,
   --  tagged records, see link above in first paragraph.

   --  We can rename objects (aliases) to make readability a bit better.
   package IO renames Ada.Text_IO;
begin
   --  We can output enumerations as names.
   IO.Put_Line ("Blue_Hue   = " &amp;  --  &amp; is the string concatenation operator.
                Blue'Image);       --  ' accesses attributes on objects.
                  --  The Image attribute converts a value to a string.
                  --  Ada 2022 has extended Image to custom types too.
                  --  Access this with -gnat2022 compiler flag.
   IO.Put_Line ("Yellow_Hue = " &amp;
                --  We can use the type's attribute.
                Primaries'Image (Yellow_Hue));

   --  We can define local variables within a declare block, this can be made
   --  more readable by giving it a label.
   Enum_IO : declare
      package Hue_IO is new IO.Enumeration_IO (Hues);

      --  Using a package makes everything inside that package visible within
      --  this block, it is good practice to only do this locally and not on
      --  a whole package within the context clause.
      use Hue_IO;
   begin
      --  We can print out the enumeration values too.
      Put (Purple); --  Note we don't have to prefix the Put procedure with
                    --  Hue_IO.
      IO.New_Line;  --  We still need to prefix with IO here.
      Put (Red_Hue);
      IO.New_Line;
   end Enum_IO;

   --  Loops have a consistent form. "&lt;form&gt; loop ... end loop".
   --  Where "form" can be "while" or "for" or missing as below, if
   --  you place the "loop ... end loop;" construct on their own lines,
   --  you can comment out or experiment with different loop constructs more
   --  easily.
   declare
      Counter : Positive := Positive'First;  --  This is 1.
   begin
      --  We can label loops so we can exit from them more easily if we need to.
      Infinite :
      loop
         IO.Put_Line ("[Infinite loop] Counter = " &amp; Counter'Image);

         Counter := Counter + 1;

         --  This next line implements a repeat ... until or do ... while loop construct.
         --  Comment it out for an infinite loop.
         exit Infinite when Counter = 5;  --  Equality tests use a single "=".
      end loop Infinite;  --  Useful when implementing state machines.
   end;

   declare  --  We don't have to have a label.
      Counter : Positive := Positive'First;  --  This is 1.
   begin
      while Counter &lt; 10
      loop
         IO.Put_Line ("Counter = " &amp; Counter'Image);

         Counter := Counter + 1;  --  There is no explicit inc/decrement.

         --  Ada 2022 introduced @ for LHS, so the above would be written as
         --  Counter := @ + 1;  --  Try it, -gnat2022.
      end loop;
   end;

   declare
      package Hue_IO is new IO.Enumeration_IO (Hues);

      --  We can have multiple packages on one line, but I tend to use one
      --  package per line for readability.
      use IO, Hue_IO;
   begin
      Put ("Hues : ");  --  Note, no prefix.

      --  Because we are using the 'Range attribute, the compiler knows it is
      --  safe and can omit run-time checks here.
      for Hue in Hues'Range
      loop
         Put (Hue);

         --  Types and objects know about their bounds, their First .. Last
         --  values. These can be specified as range types.
         if Hue /= Hues'Last then  --  The /= means "not equal to" like the
                                   --  maths symbol ≠.
            Put (", ");
         end if;
      end loop;

      IO.New_Line;
   end;

   --  All objects know their bounds, including strings.
   declare
      C : Character := Str (50);  --  Warning caused and exception raised at
                                  --  runtime.
      --  The exception raised above can only be handled by an outer scope,
      --  see wikibook link below.
   begin
      null;  --  We will never get to this point because of the above.
   end;
exception
   when Constraint_Error =&gt;
      IO.Put_Line ("Caught the exception");
end LearnAdaInY;
</code></pre>
<p>APL:</p>
<pre><code class="lang-plaintext">⍝ Comments in APL are prefixed by ⍝.

⍝ A list of numbers. (¯ is negative)
2 3e7 ¯4 50.3

⍝ An expression, showing some functions. In APL, there's
⍝ no order of operations: everything is parsed right-to-
⍝ left. This is equal to 5 + (4 × (2 ÷ (5 - 3))) = 9:
5 + 4 × 2 ÷ 5 - 3        ⍝ 9

⍝ These functions work on lists, too:
1 2 3 4 × 5              ⍝ 5 10 15 20
1 2 3 4 × 5 6 7 8        ⍝ 5 12 21 32

⍝ All functions have single-argument and dual-argument
⍝ meanings. For example, "×" applied to two arguments
⍝ means multiply, but when applied to only a right-hand
⍝ side, it returns the sign:

× ¯4 ¯2 0 2 4            ⍝ ¯1 ¯1 0 1 1

⍝ Values can be compared using these operators (1 means
⍝ "true", 0 means "false"):

10 20 30 = 10 20 99      ⍝ 1 1 0

10 20 30 &lt; 10 20 99      ⍝ 0 0 1

⍝ "⍳n" returns a vector containing the first n naturals.
⍝ Matrices can be constructed using ⍴ (reshape):
4 3 ⍴ ⍳5                 ⍝ 0 1 2
                         ⍝ 3 4 0
                         ⍝ 1 2 3
                         ⍝ 4 0 1

⍝ Single-argument ⍴ gives you the dimensions back:
⍴ 4 3 ⍴ ⍳5               ⍝ 4 3

⍝ Values can be stored using ←. Let's calculate the mean
⍝ value of a vector of numbers:
A ← 10 60 55 23

⍝ Sum of elements of A (/ is reduce):
+/A                      ⍝ 148

⍝ Length of A:
⍴A                       ⍝ 4

⍝ Mean:
(+/A) ÷ (⍴A)             ⍝ 37

⍝ We can define this as a function using {} and ⍵:
mean ← {(+/⍵)÷⍴⍵}
mean A                   ⍝ 37
</code></pre>
<p>Arturo:</p>
<pre><code class="lang-plaintext">; this is a comment
; this is another comment

;---------------------------------
; VARIABLES &amp; VALUES
;---------------------------------

; numbers
a1: 2
a2: 3.14
a3: to :complex [1 2.0]     ; 1.0+2.0i

; strings
c1: "this is a string"
c2: {
    this is a multiline string
    that is indentation-agnostic
}
c3: {:
    this is 
        a verbatim
            multiline string
                which will remain exactly
                    as the original
:}

; characters
ch: `c`

; blocks/arrays
d: [1 2 3]

; dictionaries
e: #[
    name: "John"
    surname: "Doe"
    age: 34
    likes: [pizza spaghetti]
]

; yes, functions are values too
f: function [x][
    2 * x
]

; dates
g: now              ; 2021-05-03T17:10:48+02:00

; booleans
h1: true
h2: false

;---------------------------------
; BASIC OPERATORS
;---------------------------------

; simple arithmetic
1 + 1       ; =&gt; 2
8 - 1       ; =&gt; 7
4.2 - 1.1   ; =&gt; 3.1
10 * 2      ; =&gt; 20
35 / 4      ; =&gt; 8
35 // 4     ; =&gt; 8.75
2 ^ 5       ; =&gt; 32
5 % 3       ; =&gt; 2

; bitwise operators
and 3 5     ; =&gt; 1
or 3 5      ; =&gt; 7
xor 3 5     ; =&gt; 6

; pre-defined constants
pi          ; =&gt; 3.141592653589793
epsilon     ; =&gt; 2.718281828459045
null        ; =&gt; null
true        ; =&gt; true
false       ; =&gt; false

;---------------------------------
; COMPARISON OPERATORS
;---------------------------------

; equality
1 = 1       ; =&gt; true
2 = 1       ; =&gt; false

; inequality
1 &lt;&gt; 1      ; =&gt; false
2 &lt;&gt; 1      ; =&gt; true

; more comparisons
1 &lt; 10      ; =&gt; true
1 =&lt; 10     ; =&gt; true
10 =&lt; 10    ; =&gt; true
1 &gt; 10      ; =&gt; false
1 &gt;= 10     ; =&gt; false
11 &gt;= 10    ; =&gt; true

;---------------------------------
; CONDITIONALS
;---------------------------------

; logical operators
and? true true      ; =&gt; true
and? true false     ; =&gt; false
or? true false      ; =&gt; true
or? false false     ; =&gt; false

and? [1=2][2&lt;3]     ; =&gt; false 
                    ; (the second block will not be evaluated)

; simple if statements
if 2 &gt; 1 [ print "yes!"]    ; yes!
if 3 &lt;&gt; 2 -&gt; print "true!"  ; true!

; if/else statements
if? 2 &gt; 3 -&gt; print "2 is greater than 3"
else -&gt; print "2 is not greater than 3"         ; 2 is not greater than 3

; switch statements
switch 2 &gt; 3 -&gt; print "2 is greater than 3"
             -&gt; print "2 is not greater than 3" ; 2 is not greater than 3

a: (2 &gt; 3)["yes"]["no"]         ; a: "no"
a: (2 &gt; 3)? -&gt; "yes" -&gt; "no"    ; a: "no" (exactly the same as above)

; case/when statements
case [1]
    when? [&gt;2] -&gt; print "1 is greater than 2. what?!"
    when? [&lt;0] -&gt; print "1 is less than 0. nope..."
    else -&gt; print "here we are!"                ; here we are!

;---------------------------------
; LOOPS
;---------------------------------

; with `loop`
arr: [1 4 5 3]
loop arr 'x [
    print ["x =" x]
]
; x = 1
; x = 4
; x = 5
; x = 3

; with loop and custom index
loop.with:'i arr 'x [
    print ["item at position" i "=&gt;" x]
]
; item at position 0 =&gt; 1
; item at position 1 =&gt; 4
; item at position 2 =&gt; 5
; item at position 3 =&gt; 3

; using ranges
loop 1..3 'x -&gt;         ; since it's a single statement
    print x             ; there's no need for [block] notation
                        ; we can wrap it up using the `-&gt;` syntactic sugar

loop `a`..`c` 'ch -&gt;
    print ch
; a
; b
; c

; picking multiple items
loop 1..10 [x y] -&gt;
    print ["x =" x ", y =" y]
; x = 1 , y = 2 
; x = 3 , y = 4 
; x = 5 , y = 6 
; x = 7 , y = 8 
; x = 9 , y = 10 

; looping through a dictionary
dict: #[name: "John", surname: "Doe", age: 34]
loop dict [key value][
    print [key "-&gt;" value]
]
; name -&gt; John 
; surname -&gt; Doe 
; age -&gt; 34 

; while loops
i: new 0
while [i&lt;3][
    print ["i =" i]
    inc 'i
]
; i = 0
; i = 1
; i = 2

;---------------------------------
; STRINGS
;---------------------------------

; case
a: "tHis Is a stRinG"
print upper a               ; THIS IS A STRING
print lower a               ; this is a string
print capitalize a          ; tHis Is a stRinG

; concatenation
a: "Hello " ++ "World!"     ; a: "Hello World!"

; strings as an array
split "hello"               ; =&gt; [h e l l o]
split.words "hello world"   ; =&gt; [hello world]

print first "hello"         ; h
print last "hello"          ; o

; conversion
to :string 123              ; =&gt; "123"
to :integer "123"           ; =&gt; 123

; joining strings together
join ["hello" "world"]              ; =&gt; "helloworld"
join.with:"-" ["hello" "world"]     ; =&gt; "hello-world"

; string interpolation
x: 2
print ~"x = |x|"            ; x = 2

; interpolation with `print`
print ["x =" x]             ; x = 2
                            ; (`print` works by calculating the given block
                            ;  and joining the different values as strings
                            ;  with a single space between them)

; templates
print render.template {
    &lt;||= switch x=2 [ ||&gt;
        Yes, x = 2
    &lt;||][||&gt;
        No, x is not 2
    &lt;||]||&gt; 
} ; Yes, x = 2

; matching
prefix? "hello" "he"        ; =&gt; true
suffix? "hello" "he"        ; =&gt; false

contains? "hello" "ll"      ; =&gt; true
contains? "hello" "he"      ; =&gt; true
contains? "hello" "x"       ; =&gt; false

in? "ll" "hello"            ; =&gt; true 
in? "x" "hello"             ; =&gt; false

;---------------------------------
; BLOCKS
;---------------------------------

; calculate a block
arr: [1 1+1 1+1+1]
@arr                        ; =&gt; [1 2 3]

; execute a block
sth: [print "Hello world"]  ; this is perfectly valid,
                            ; could contain *anything*
                            ; and will not be executed...

do sth                      ; Hello world
                            ; (...until we tell it to)

; array indexing
arr: ["zero" "one" "two" "three"]
print first arr             ; zero
print arr\0                 ; zero
print last arr              ; three
print arr\3                 ; three

x: 2
print get arr x             ; two
print arr \ 2               ; two
                            ; (using the `\` infix alias for get -
                            ;  notice space between the operands! 
                            ;  otherwise, it'll be parsed as a path)

; setting an array element
arr\0: "nada"
set arr 2 "dos"
print arr                   ; nada one dos three

; adding elements to an array
arr: new []
'arr ++ "one"
'arr ++ "two"
print arr                   ; one two

; remove elements from an array
arr: new ["one" "two" "three" "four"]
'arr -- "two"               ; arr: ["one" "three" "four"]
remove 'arr .index 0        ; arr: ["three" "four"]

; getting the size of an array
arr: ["one" 2 "three" 4]
print size arr              ; 4

; getting a slice of an array
print slice ["one" "two" "three" "four"] 0 1        ; one two

; check if array contains a specific element
print contains? arr "one"   ; true
print contains? arr "five"  ; false

; sorting array
arr: [1 5 3 2 4]
sort arr                    ; =&gt; [1 2 3 4 5]
sort.descending arr         ; =&gt; [5 4 3 2 1]

; mapping values
map 1..10 [x][2*x]          ; =&gt; [2 4 6 8 10 12 14 16 18 20]
map 1..10 'x -&gt; 2*x         ; same as above
map 1..10 =&gt; [2*&amp;]          ; same as above
map 1..10 =&gt; [2*]           ; same as above

; selecting/filtering array values
select 1..10 [x][odd? x]    ; =&gt; [1 3 5 7 9]
select 1..10 =&gt; odd?        ; same as above

filter 1..10 =&gt; odd?        ; =&gt; [2 4 6 8 10]
                            ; (now, we leave out all odd numbers - 
                            ;  while select keeps them)

; misc operations
arr: ["one" 2 "three" 4]
reverse arr                 ; =&gt; [4 "three" 2 "one"]
shuffle arr                 ; =&gt; [2 4 "three" "one"]
unique [1 2 3 2 3 1]        ; =&gt; [1 2 3]
permutate [1 2 3]           ; =&gt; [[1 2 3] [1 3 2] [3 1 2] [2 1 3] [2 3 1] [3 2 1]]
take 1..10 3                ; =&gt; [1 2 3]
repeat [1 2] 3              ; =&gt; [1 2 1 2 1 2]

;---------------------------------
; FUNCTIONS
;---------------------------------

; declaring a function
f: function [x][ 2*x ]
f: function [x]-&gt; 2*x       ; same as above
f: $[x]-&gt;2*x                ; same as above (only using the `$` alias 
                            ;  for the `function`... function)

; calling a function
f 10                        ; =&gt; 20

; returning a value
g: function [x][
    if x &lt; 2 -&gt; return 0

    res: 0
    loop 0..x 'z [
        res: res + z
    ]
    return res
]

;---------------------------------
; CUSTOM TYPES
;---------------------------------

; defining a custom type
define :person [                            ; define a new custom type "Person"
    name                                    ; with fields: name, surname, age
    surname
    age 
][ 
    ; with custom post-construction initializer
    init: [
        this\name: capitalize this\name
    ]

    ; custom print function
    print: [
        render "NAME: |this\name|, SURNAME: |this\surname|, AGE: |this\age|"
    ]

    ; custom comparison operator
    compare: 'age
]

; create a method for our custom type
sayHello: function [this][
    ensure -&gt; is? :person this

    print ["Hello" this\name]
]

; create new objects of our custom type
a: to :person ["John" "Doe" 34]                 ; let's create 2 "Person"s
b: to :person ["jane" "Doe" 33]                 ; and another one

; call pseudo-inner method
sayHello a                                      ; Hello John                       
sayHello b                                      ; Hello Jane

; access object fields
print ["The first person's name is:" a\name]    ; The first person's name is: John
print ["The second person's name is:" b\name]   ; The second person's name is: Jane

; changing object fields
a\name: "Bob"                                   
sayHello a                                      ; Hello Bob

; verifying object type
print type a                                    ; :person
print is? :person a                             ; true

; printing objects
print a                                         ; NAME: John, SURNAME: Doe, AGE: 34

; sorting user objects (using custom comparator)
sort @[a b]                                     ; Jane..., John...
sort.descending @[a b]                          ; John..., Jane...
</code></pre>
<p>AssemblyScript:</p>
<pre><code class="lang-plaintext">// There are many basic types in AssemblyScript,
let isDone: boolean = false;
let name: string = "Anders";

// but integer type come as signed (sized from 8 to 64 bits)
let lines8: i8 = 42;
let lines16: i16 = 42;
let lines32: i32 = 42;
let lines64: i64 = 42;

// and unsigned (sized from 8 to 64 bits),
let ulines8: u8 = 42;
let ulines16: u16 = 42;
let ulines32: u32 = 42;
let ulines64: u64 = 42;

// and float has two sizes possible (32/64).
let rate32: f32 = 1.0
let rate64: f64 = 1.0

// But you can omit the type annotation if the variables are derived
// from explicit literals
let _isDone = false;
let _lines = 42;
let _name = "Anders";

// Use const keyword for constants
const numLivesForCat = 9;
numLivesForCat = 1; // Error

// For collections, there are typed arrays and generic arrays
let list1: i8[] = [1, 2, 3];
// Alternatively, using the generic array type
let list2: Array&lt;i8&gt; = [1, 2, 3];

// For enumerations:
enum Color { Red, Green, Blue };
let c: Color = Color.Green;

// Functions imported from JavaScript need to be declared as external
// @ts-ignore decorator
@external("alert")
declare function alert(message: string): void;

// and you can also import JS functions in a namespace
declare namespace window {
  // @ts-ignore decorator
  @external("window", "alert")
  function alert(message: string): void;
}

// Lastly, "void" is used in the special case of a function returning nothing
export function bigHorribleAlert(): void {
  alert("I'm a little annoying box!"); // calling JS function here
}

// Functions are first class citizens, support the lambda "fat arrow" syntax

// The following are equivalent, the compiler does not offer any type
// inference for functions yet, and same WebAssembly will be emitted.
export function f1 (i: i32): i32 { return i * i; }
// "Fat arrow" syntax
let f2 = (i: i32): i32 =&gt; { return i * i; }
// "Fat arrow" syntax, braceless means no return keyword needed
let f3 = (i: i32): i32 =&gt; i * i;

// Classes - members are public by default
export class Point {
  // Properties
  x: f64;

  // Constructor - the public/private keywords in this context will generate
  // the boiler plate code for the property and the initialization in the
  // constructor.
  // In this example, "y" will be defined just like "x" is, but with less code
  // Default values are also supported

  constructor(x: f64, public y: f64 = 0) {
    this.x = x;
  }

  // Functions
  dist(): f64 { return Math.sqrt(this.x * this.x + this.y * this.y); }

  // Static members
  static origin: Point = new Point(0, 0);
}

// Classes can be explicitly marked as extending a parent class.
// Any missing properties will then cause an error at compile-time.
export class PointPerson extends Point {
  constructor(x: f64, y: f64, public name: string) {
    super(x, y);
  }
  move(): void {}
}

let p1 = new Point(10, 20);
let p2 = new Point(25); //y will be 0

// Inheritance
export class Point3D extends Point {
  constructor(x: f64, y: f64, public z: f64 = 0) {
    super(x, y); // Explicit call to the super class constructor is mandatory
  }

  // Overwrite
  dist(): f64 {
    let d = super.dist();
    return Math.sqrt(d * d + this.z * this.z);
  }
}

// Namespaces, "." can be used as separator for sub namespaces
export namespace Geometry {
  class Square {
    constructor(public sideLength: f64 = 0) {
    }
    area(): f64 {
      return Math.pow(this.sideLength, 2);
    }
  }
}

let s1 = new Geometry.Square(5);

// Generics
// AssemblyScript compiles generics to one concrete method or function per set
// of unique contextual type arguments, also known as [monomorphisation].
// Implications are that a module only includes and exports concrete functions
// for sets of type arguments actually used and that concrete functions can be
// shortcutted with [static type checks] at compile time, which turned out to
// be quite useful.
// Classes
export class Tuple&lt;T1, T2&gt; {
  constructor(public item1: T1, public item2: T2) {
  }
}

export class Pair&lt;T&gt; {
  item1: T;
  item2: T;
}

// And functions
export function pairToTuple &lt;T&gt;(p: Pair&lt;T&gt;): Tuple&lt;T, T&gt; {
  return new Tuple(p.item1, p.item2);
};

let tuple = pairToTuple&lt;string&gt;({ item1: "hello", item2: "world" });

// Including references to a TypeScript-only definition file:
/// &lt;reference path="jquery.d.ts" /&gt;

// Template Strings (strings that use backticks)
// String Interpolation with Template Strings
let name = 'Tyrone';
let greeting = `Hi ${name}, how are you?`
// Multiline Strings with Template Strings
let multiline = `This is an example
of a multiline string`;

let numbers: Array&lt;i8&gt; = [0, 1, 2, 3, 4];
let moreNumbers: Array&lt;i8&gt; = numbers;
moreNumbers[5] = 5; // Error, elements are read-only
moreNumbers.push(5); // Error, no push method (because it mutates array)
moreNumbers.length = 3; // Error, length is read-only
numbers = moreNumbers; // Error, mutating methods are missing

// Type inference in Arrays
let ints = [0, 1, 2, 3, 4]  // will infer as Array&lt;i32&gt;
let floats: f32[] = [0, 1, 2, 3, 4]  // will infer as Array&lt;f32&gt;
let doubles = [0.0, 1.0, 2, 3, 4]  // will infer as Array&lt;f64&gt;
let bytes1 = [0 as u8, 1, 2, 3, 4]  // will infer as Array&lt;u8&gt;
let bytes2 = [0, 1, 2, 3, 4]  as u8[] // will infer as Array&lt;u8&gt;
let bytes3: u8[] = [0, 1, 2, 3, 4] // will infer as Array&lt;u8&gt;
</code></pre>
<p>ATS:</p>
<pre><code class="lang-plaintext">// Include the standard library
#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"

// To compile, either use
//   $ patscc -DATS_MEMALLOC_LIBC program.dats -o program
// or install the ats-acc wrapper https://github.com/sparverius/ats-acc and use
//   $ acc pc program.dats

// C-style line comments
/* and C-style block comments */
(* as well as ML-style block comments *)

/*************** Part 1: the ML fragment ****************/

val () = print "Hello, World!\n"

// No currying
fn add (x: int, y: int) = x + y

// fn vs fun is like the difference between let and let rec in OCaml/F#
fun fact (n: int): int = if n = 0 then 1 else n * fact (n-1)

// Multi-argument functions need parentheses when you call them; single-argument
// functions can omit parentheses
val forty_three = add (fact 4, 19)

// let is like let in SML
fn sum_and_prod (x: int, y: int): (int, int) =
  let
    val sum = x + y
    val prod = x * y
  in (sum, prod) end

// 'type' is the type of all heap-allocated, non-linear types
// Polymorphic parameters go in {} after the function name
fn id {a:type} (x: a) = x

// ints aren't heap-allocated, so we can't pass them to 'id'
// val y: int = id 7 // doesn't compile

// 't@ype' is the type of all non-linear potentially unboxed types. It is a
// supertype of 'type'.
// Templated parameters go in {} before the function name
fn {a:t@ype} id2 (x: a) = x

val y: int = id2 7 // works

// can't have polymorphic t@ype parameters
// fn id3 {a:t@ype} (x: a) = x // doesn't compile

// explicity specifying type parameters:
fn id4 {a:type} (x: a) = id {a} x // {} for non-template parameters
fn id5 {a:type} (x: a) = id2&lt;a&gt; x // &lt;&gt; for template parameters
fn id6 {a:type} (x: a) = id {..} x // {..} to explicitly infer it

// Heap allocated shareable datatypes
// using datatypes leaks memory
datatype These (a:t@ype, b:t@ype) = This of a
                                  | That of b
                                  | These of (a, b)

// Pattern matching using 'case'
fn {a,b: t@ype} from_these (x: a, y: b, these: These(a,b)): (a, b) =
  case these of
  | This(x) =&gt; (x, y) // Shadowing of variable names is fine; here, x shadows
                      // the parameter x
  | That(y) =&gt; (x, y)
  | These(x, y) =&gt; (x, y)

// Partial pattern match using 'case-'
// Will throw an exception if passed This
fn {a,b:t@ype} unwrap_that (these: These(a,b)): b =
  case- these of
  | That(y) =&gt; y
  | These(_, y) =&gt; y


/*************** Part 2: refinements ****************/

// Parameterize functions by what values they take and return
fn cool_add {n:int} {m:int} (x: int n, y: int m): int (n+m) = x + y

// list(a, n) is a list of n a's
fun square_all {n:int} (xs: list(int, n)): list(int, n) =
  case xs of
  | list_nil() =&gt; list_nil()
  | list_cons(x, rest) =&gt; list_cons(x * x, square_all rest)

fn {a:t@ype} get_first {n:int | n &gt;= 1} (xs: list(a, n)): a =
  case+ xs of // '+' asks ATS to prove it's total
  | list_cons(x, _) =&gt; x

// Can't run get_first on lists of length 0
// val x: int = get_first (list_nil()) // doesn't compile

// in the stdlib:
// sortdef nat = {n:int | n &gt;= 0}
// sortdef pos = {n:int | n &gt;= 1}

fn {a:t@ype} also_get_first {n:pos} (xs: list(a, n)): a =
  let
    val+ list_cons(x, _) = xs // val+ also works
  in x end

// tail-recursive reverse
fun {a:t@ype} reverse {n:int} (xs: list(a, n)): list(a, n) =
  let
    // local functions can use type variables from their enclosing scope
    // this one uses both 'a' and 'n'
    fun rev_helper {i:nat} (xs: list(a, n-i), acc: list(a, i)): list(a, n) =
      case xs of
      | list_nil() =&gt; acc
      | list_cons(x, rest) =&gt; rev_helper(rest, list_cons(x, acc))
  in rev_helper(xs, list_nil) end

// ATS has three context-dependent namespaces
// the two 'int's mean different things in this example, as do the two 'n's
fn namespace_example {n:int} (n: int n): int n = n
//                      ^^^                         sort namespace
//                    ^          ^^^ ^   ^^^ ^      statics namespace
// ^^^^^^^^^^^^^^^^^          ^                  ^  value namespace

// a termination metric can go in .&lt; &gt;.
// it must decrease on each recursive call
// then ATS will prove it doesn't infinitely recurse
fun terminating_factorial {n:nat} .&lt;n&gt;. (n: int n): int =
  if n = 0 then 1 else n * terminating_factorial (n-1)


/*************** Part 3: the LF fragment ****************/

// ATS supports proving theorems in LF (http://twelf.org/wiki/LF)

// Relations are represented by inductive types

// Proofs that the nth fibonacci number is f
dataprop Fib(n:int, m:int) =
  | FibZero(0, 0)
  | FibOne(1, 1)
  | {n, f1, f2: int} FibInd(n, f1 + f2) of (Fib(n-1,f1), Fib(n-2,f2))

// Proved-correct fibonacci implementation
// [A] B is an existential type: "there exists A such that B"
// (proof | value)
fun fib {n:nat} .&lt;n&gt;. (n: int n): [f:int] (Fib(n,f) | int f) =
  if n = 0 then (FibZero | 0) else
  if n = 1 then (FibOne | 1) else
  let
    val (proof1 | val1) = fib (n-1)
    val (proof2 | val2) = fib (n-2)
  // the existential type is inferred
  in (FibInd(proof1, proof2) | val1 + val2) end

// Faster proved-correct fibonacci implementation
fn fib_tail {n:nat} (n: int n): [f:int] (Fib(n,f) | int f) =
  let
    fun loop {i:int | i &lt; n} {f1, f2: int} .&lt;n - i&gt;.
          (p1: Fib(i,f1), p2: Fib(i+1,f2)
          | i: int i, f1: int f1, f2: int f2, n: int n
          ): [f:int] (Fib(n,f) | int f) =
      if i = n - 1
      then (p2 | f2)
      else loop (p2, FibInd(p2,p1) | i+1, f2, f1+f2, n)
  in if n = 0 then (FibZero | 0) else loop (FibZero, FibOne | 0, 0, 1, n) end

// Proof-level lists of ints, of type 'sort'
datasort IntList = ILNil of ()
                 | ILCons of (int, IntList)

// ILAppend(x,y,z) iff x ++ y = z
dataprop ILAppend(IntList, IntList, IntList) =
  | {y:IntList} AppendNil(ILNil, y, y)
  | {a:int} {x,y,z: IntList}
    AppendCons(ILCons(a,x), y, ILCons(a,z)) of ILAppend(x,y,z)

// prfuns/prfns are compile-time functions acting on proofs

// metatheorem: append is total
prfun append_total {x,y: IntList} .&lt;x&gt;. (): [z:IntList] ILAppend(x,y,z)
  = scase x of // scase lets you inspect static arguments (only in prfuns)
  | ILNil() =&gt; AppendNil
  | ILCons(a,rest) =&gt; AppendCons(append_total())


/*************** Part 4: views ****************/

// views are like props, but linear; ie they must be consumed exactly once
// prop is a subtype of view

// 'type @ address' is the most basic view

fn {a:t@ype} read_ptr {l:addr} (pf: a@l | p: ptr l): (a@l | a) =
  let
    // !p searches for usable proofs that say something is at that address
    val x = !p
  in (pf | x) end

// oops, tried to dereference a potentially invalid pointer
// fn {a:t@ype} bad {l:addr} (p: ptr l): a = !p // doesn't compile

// oops, dropped the proof (leaked the memory)
// fn {a:t@ype} bad {l:addr} (pf: a@l | p: ptr l): a = !p // doesn't compile

fn inc_at_ptr {l:addr} (pf: int@l | p: ptr l): (int@l | void) =
  let
    // !p := value writes value to the location at p
    // like !p, it implicitly searches for usable proofs that are in scope
    val () = !p := !p + 1
  in (pf | ()) end

// threading proofs through gets annoying
fn inc_three_times {l:addr} (pf: int@l | p: ptr l): (int@l | void) =
  let
    val (pf2 | ()) = inc_at_ptr (pf | p)
    val (pf3 | ()) = inc_at_ptr (pf2 | p)
    val (pf4 | ()) = inc_at_ptr (pf3 | p)
  in (pf4 | ()) end

// so there's special syntactic sugar for when you don't consume a proof
fn dec_at_ptr {l:addr} (pf: !int@l | p: ptr l): void =
  !p := !p - 1           // ^ note the exclamation point

fn dec_three_times {l:addr} (pf: !int@l | p: ptr l): void =
  let
    val () = dec_at_ptr (pf | p)
    val () = dec_at_ptr (pf | p)
    val () = dec_at_ptr (pf | p)
  in () end

// dataview is like dataprop, but linear
// A proof that either the address is null, or there is a value there
dataview MaybeNull(a:t@ype, addr) =
  | NullPtr(a, null)
  | {l:addr | l &gt; null} NonNullPtr(a, l) of (a @ l)

fn maybe_inc {l:addr} (pf: !MaybeNull(int, l) | p: ptr l): void =
  if ptr1_is_null p
  then ()
  else let
    // Deconstruct the proof to access the proof of a @ l
    prval NonNullPtr(value_exists) = pf
    val () = !p := !p + 1
    // Reconstruct it again for the caller
    prval () = pf := NonNullPtr(value_exists)
  in () end

// array_v(a,l,n) represents and array of n a's at location l
// this gets compiled into an efficient for loop, since all proofs are erased
fn sum_array {l:addr}{n:nat} (pf: !array_v(int,l,n) | p: ptr l, n: int n): int =
  let
    fun loop {l:addr}{n:nat} .&lt;n&gt;. (
      pf: !array_v(int,l,n)
    | ptr: ptr l,
      length: int n,
      acc: int
    ): int = if length = 0
      then acc
      else let
        prval (head, rest) = array_v_uncons(pf)
        val result = loop(rest | ptr_add&lt;int&gt;(ptr, 1), length - 1, acc + !ptr)
        prval () = pf := array_v_cons(head, rest)
      in result end
  in loop (pf | p, n, 0) end

// 'var' is used to create stack-allocated (lvalue) variables
val seven: int = let
    var res: int = 3
    // they can be modified
    val () = res := res + 1
    // addr@ res is a pointer to it, and view@ res is the associated proof
    val (pf | ()) = inc_three_times(view@ res | addr@ res)
    // need to give back the view before the variable goes out of scope
    prval () = view@ res := pf
  in res end

// References let you pass lvalues, like in C++
fn square (x: &amp;int): void =
  x := x * x // they can be modified

val sixteen: int = let
    var res: int = 4
    val () = square res
  in res end

fn inc_at_ref (x: &amp;int): void =
  let
    // like vars, references have views and addresses
    val (pf | ()) = inc_at_ptr(view@ x | addr@ x)
    prval () = view@ x := pf
  in () end

// Like ! for views, &amp; references are only legal as argument types
// fn bad (x: &amp;int): &amp;int = x // doesn't compile

// this takes a proof int n @ l, but returns a proof int (n+1) @ l
// since they're different types, we can't use !int @ l like before
fn refined_inc_at_ptr {n:int}{l:addr} (
  pf: int n @ l | p: ptr l
): (int (n+1) @ l | void) =
  let
    val () = !p := !p + 1
  in (pf | ()) end

// special syntactic sugar for returning a proof at a different type
fn refined_dec_at_ptr {n:int}{l:addr} (
  pf: !int n @ l &gt;&gt; int (n-1) @ l | p: ptr l
): void =
  !p := !p - 1

// legal but very bad code
prfn swap_proofs {v1,v2:view} (a: !v1 &gt;&gt; v2, b: !v2 &gt;&gt; v1): void =
  let
    prval tmp = a
    prval () = a := b
    prval () = b := tmp
  in () end

// also works with references
fn refined_square {n:int} (x: &amp;int n &gt;&gt; int (n*n)): void =
  x := x * x

fn replace {a,b:vtype} (dest: &amp;a &gt;&gt; b, src: b): a =
  let
    val old = dest
    val () = dest := src
  in old end

// values can be uninitialized
fn {a:vt@ype} write (place: &amp;a? &gt;&gt; a, value: a): void =
  place := value

val forty: int = let
    var res: int
    val () = write (res, 40)
  in res end

// viewtype: a view and a type
viewtypedef MaybeNullPtr(a:t@ype) = [l:addr] (MaybeNull(a, l) | ptr l)
// MaybeNullPtr has type 'viewtype' (aka 'vtype')
// type is a subtype of vtype and t@ype is a subtype of vt@ype

// The most general identity function:
fn {a:vt@ype} id7 (x: a) = x

// since they contain views, viewtypes must be used linearly
// fn {a:vt@ype} duplicate (x: a) = (x, x) // doesn't compile
// fn {a:vt@ype} ignore (x: a) = () // doesn't compile

// arrayptr(a,l,n) is a convenient built-in viewtype
fn easier_sum_array {l:addr}{n:nat} (p: !arrayptr(int,l,n), n: int n): int =
  let
    fun loop {i:nat | i &lt;= n} (
      p: !arrayptr(int,l,n), n: int n, i: int i, acc: int
    ): int =
      if i = n
      then acc
      else loop(p, n, i+1, acc + p[i])
  in loop(p, n, 0, 0) end


/*************** Part 5: dataviewtypes ****************/

// a dataviewtype is a heap-allocated non-shared inductive type

// in the stdlib:
// dataviewtype list_vt(a:vt@ype, int) =
//   | list_vt_nil(a, 0)
//   | {n:nat} list_vt_cons(a, n+1) of (a, list_vt(a, n))

fn {a:vt@ype} length {n:int} (l: !list_vt(a, n)): int n =
  let                         // ^ since we're not consuming it
    fun loop {acc:int} (l: !list_vt(a, n-acc), acc: int acc): int n =
      case l of
      | list_vt_nil() =&gt; acc
      | list_vt_cons(head, tail) =&gt; loop(tail, acc + 1)
  in loop (l, 0) end

//     vvvvv  not vt@ype, because you can't easily get rid of a vt@ype
fun {a:t@ype} destroy_list {n:nat} (l: list_vt(a,n)): void =
  case l of
  // ~ pattern match consumes and frees that node
  | ~list_vt_nil() =&gt; ()
  | ~list_vt_cons(_, tail) =&gt; destroy_list tail

// unlike a datatype, a dataviewtype can be modified:
fun {a:vt@ype} push_back {n:nat} (
  x: a,
  l: &amp;list_vt(a,n) &gt;&gt; list_vt(a,n+1)
): void =
  case l of
  | ~list_vt_nil() =&gt; l := list_vt_cons(x, list_vt_nil)
  // @ pattern match disassembles/"unfolds" the datavtype's view, so you can
  // modify its components
  | @list_vt_cons(head, tail) =&gt; let
      val () = push_back (x, tail)
      // reassemble it with fold@
      prval () = fold@ l
    in () end

fun {a:vt@ype} pop_last {n:pos} (l: &amp;list_vt(a,n) &gt;&gt; list_vt(a,n-1)): a =
  let
    val+ @list_vt_cons(head, tail) = l
  in case tail of
    | list_vt_cons _ =&gt; let
        val res = pop_last tail
        prval () = fold@ l
      in res end
    | ~list_vt_nil() =&gt; let
        val head = head
        // Deallocate empty datavtype nodes with free@
        val () = free@{..}{0} l
        val () = l := list_vt_nil()
      in head end
 /** Equivalently:
  * | ~list_vt_nil() =&gt; let
  *     prval () = fold@ l
  *     val+ ~list_vt_cons(head, ~list_vt_nil()) = l
  *     val () = l := list_vt_nil()
  *   in head end
  */
  end

// "holes" (ie uninitialized memory) can be created with _ on the RHS
// This function uses destination-passing-style to copy the list in a single
// tail-recursive pass.
fn {a:t@ype} copy_list {n:nat} (l: !list_vt(a, n)): list_vt(a, n) =
  let
    var res: ptr
    fun loop {k:nat} (l: !list_vt(a, k), hole: &amp;ptr? &gt;&gt; list_vt(a, k)): void =
      case l of
      | list_vt_nil() =&gt; hole := list_vt_nil
      | list_vt_cons(first, rest) =&gt; let
          val () = hole := list_vt_cons{..}{k-1}(first, _)
          //                                            ^ on RHS: a hole
          val+list_vt_cons(_, new_hole) = hole
          //               ^ on LHS: wildcard pattern (not a hole)
          val () = loop (rest, new_hole)
          prval () = fold@ hole
        in () end
    val () = loop (l, res)
  in res end

// Reverse a linked-list *in place* -- no allocations or frees
fn {a:vt@ype} in_place_reverse {n:nat} (l: list_vt(a, n)): list_vt(a, n) =
  let
    fun loop {k:nat} (l: list_vt(a, n-k), acc: list_vt(a, k)): list_vt(a, n) =
      case l of
      | ~list_vt_nil() =&gt; acc
      | @list_vt_cons(x, tail) =&gt; let
          val rest = replace(tail, acc)
          // the node 'l' is now part of acc instead of the original list
          prval () = fold@ l
        in loop (rest, l) end
  in loop (l, list_vt_nil) end


/*************** Part 6: miscellaneous extras ****************/

// a record
// Point has type 't@ype'
typedef Point = @{ x= int, y= int }
val origin: Point = @{ x= 0, y= 0 }

// tuples and records are normally unboxed, but there are boxed variants
// BoxedPoint has type 'type'
typedef BoxedPoint = '{ x= int, y= int }
val boxed_pair: '(int,int) = '(5, 3)

// When passing a pair as the single argument to a function, it needs to be
// written @(a,b) to avoid ambiguity with multi-argument functions
val six_plus_seven = let
    fun sum_of_pair (pair: (int,int)) = pair.0 + pair.1
  in sum_of_pair @(6, 7) end

// When a constructor has no associated data, such as None(), the parentheses
// are optional in expressions.  However, they are mandatory in patterns
fn inc_option (opt: Option int) =
  case opt of
  | Some(x) =&gt; Some(x+1)
  | None() =&gt; None

// ATS has a simple FFI, since it compiles to C and (mostly) uses the C ABI
%{
// Inline C code
int scanf_wrapper(void *format, void *value) {
    return scanf((char *) format, (int *) value);
}
%}
// If you wanted to, you could define a custom dataviewtype more accurately
// describing the result of scanf
extern fn scanf (format: string, value: &amp;int): int = "scanf_wrapper"

fn get_input_number (): Option int =
  let
    var x: int = 0
  in
    if scanf("%d\n", x) = 1
    then Some(x)
    else None
  end

// extern is also used for separate declarations and definitions
extern fn say_hi (): void
// later on, or in another file:
implement say_hi () = print "hi\n"

// if you implement main0, it will run as the main function
// implmnt is an alias for implement
implmnt main0 () = ()

// as well as for axioms:
extern praxi view_id {a:view} (x: a): a
// you don't need to actually implement the axioms, but you could
primplmnt view_id x = x
// primplmnt is an alias for primplement

// Some standard aliases are:
// List0(a) = [n:nat] list(a,n) and List0_vt(a) = [n:nat] list_vt(a,n)
// t0p = t@ype and vt0p = vt@ype
fun {a:t0p} append (xs: List0 a, ys: List0 a): List0 a =
  case xs of
  | list_nil() =&gt; ys
  | list_cons(x, xs) =&gt; list_cons(x, append(xs, ys))

// there are many ways of doing things after one another
val let_in_example = let
    val () = print "thing one\n"
    val () = print "thing two\n"
  in () end

val parens_example = (print "thing one\n"; print "thing two\n")

val begin_end_example = begin
    print "thing one\n";
    print "thing two\n"; // optional trailing semicolon
  end

// and many ways to use local variables
fun times_four_let x =
  let
    fun times_two (x: int) = x * 2
  in times_two (times_two x) end

local
  fun times_two (x: int) = x * 2
in
  fun times_four_local x = times_two (times_two x)
end

fun times_four_where x = times_two (times_two x)
  where {
    fun times_two (x: int) = x * 2
  }

//// The last kind of comment in ATS is an end-of-file comment.

Anything between the four slashes and the end of the file is ignored.

Have fun with ATS!
</code></pre>
<p>Ballerina:</p>
<pre><code class="lang-plaintext">// Single-line comment

// Import modules into the current source file 
import ballerina/io;
import ballerina/time;
import ballerina/http;
import ballerinax/java.jdbc;
import ballerina/lang.'int as ints;
import ballerinax/awslambda;
// Module alias "af" used in code in place of the full module name
import ballerinax/azure.functions as af;

http:Client clientEP = new ("https://freegeoip.app/");
jdbc:Client accountsDB = new ({url: "jdbc:mysql://localhost:3306/AccountsDB", 
                               username: "test", password: "test"});

// A service is a first-class concept in Ballerina, and is one of the 
// entrypoints to a Ballerina program. 
// The Ballerina platform also provides support for easy deployment to 
// environments such as Kubernetes (https://ballerina.io/learn/deployment/kubernetes/).
service geoservice on new http:Listener(8080) {

    @http:ResourceConfig {
        path: "/geoip/{ip}"
    }
    resource function geoip(http:Caller caller, http:Request request,
                            string ip) returns @tainted error? {
        http:Response resp = check clientEP-&gt;get("/json/" + &lt;@untainted&gt;ip);
        check caller-&gt;respond(&lt;@untainted&gt; check resp.getTextPayload());
    }

}

// Serverless Function-as-a-Service support with AWS Lambda.
// The Ballerina compiler automatically generates the final deployment 
// artifact to be deployed.
@awslambda:Function
public function echo(awslambda:Context ctx, json input) returns json {
    return input;
}

@awslambda:Function
public function notifyS3(awslambda:Context ctx, 
                         awslambda:S3Event event) returns json {
    return event.Records[0].s3.'object.key;
}

// Serverless Function-as-a-Service support with Azure Functions.
// Similar to AWS Lambda, the compiler generates the deployment artifacts.
@af:Function
public function fromQueueToQueue(af:Context ctx, 
        @af:QueueTrigger { queueName: "queue1" } string inMsg,
        @af:QueueOutput { queueName: "queue2" } af:StringOutputBinding outMsg) {
    outMsg.value = inMsg;
}

// A custom record type
public type Person record {
    string id;              // required field
    string name;            
    int age?;               // optional field
    string country = "N/A"; // default value
};

@af:Function
public function fromHttpTriggerCosmosDBInput(
        @af:HTTPTrigger { route: "c1/{country}" } af:HTTPRequest httpReq, 
        @af:CosmosDBInput { connectionStringSetting: "CosmosDBConnection", 
        databaseName: "db1", collectionName: "c1", 
        sqlQuery: "select * from c1 where c1.country = {country}" } 
        Person[] dbReq)
        returns @af:HTTPOutput string|error {
    return dbReq.toString();
}

public function main() returns @tainted error? {
    int a = 10;               // 64-bit signed integer
    float b = 1.56;           // 64-bit IEEE 754-2008 binary floating point number
    string c = "hello";       // a unicode string
    boolean d = true;         // true, false
    decimal e = 15.335;       // decimal floating point number

    var f = 20;               // type inference with 'var' - 'f' is an int

    int[] intArray = [1, 2, 3, 4, 5, 6];
    int x = intArray.shift(); // similar to a dequeue operation
    x = intArray.pop();       // removes the last element
    intArray.push(10);        // add to the end

    // Tuples - similar to a fixed length array with a distinct type for each slot
    [string, int] p1 = ["Jack", 1990]; 
    [string, int] p2 = ["Tom", 1986];
    io:println("Name: ", p1[0], " Birth Year: ", p1[1]);

    string name1;
    int birthYear1;
    [name1, birthYear1] = p1;     // tuple destructuring

    var [name2, birthYear2] = p2; // declare and assign values in the same statement

    // If statements
    int ix = 10;
    if ix &lt; 10 {
        io:println("value is less than 10");
    } else if ix == 10 {
        io:println("value equals to 10");
    } else {
        io:println("value is greater than 10");
    }

    // Loops
    int count = 10;
    int i = 0;
    while i &lt; 10 {
        io:println(i);
    }
    // Loop from 0 to count (inclusive)
    foreach var j in 0...count {
        io:println(j);
    }
    // Loop from 0 to count (non-inclusive)
    foreach var j in 0..&lt;count {
        io:println(j);
    }
    // Loop a list
    foreach var j in intArray {
        io:println(j);
    }

    json j1 = { "name" : name1, "birthYear" : birthYear1, "zipcode" : 90210 };
    io:println(j1.name, " - ", j1.zipcode);
    // New fields are added to a JSON value through "mergeJson"
    var j2 = j1.mergeJson({ "id" : "90400593053"});

    // XML namespace declaration
    xmlns "http://example.com/ns1" as ns1;
    xmlns "http://example.com/default";

    // XML variable from a literal value
    xml x1 = xml `&lt;ns1:entry&gt;&lt;name&gt;{{name1}}&lt;/name&gt;&lt;birthYear&gt;{{birthYear1}}&lt;/birthYear&gt;&lt;/ns1:entry&gt;`;
    io:println(x1);
    // Access specific elements in the XML value
    io:println(x1/&lt;name&gt;);
    // List all child items in the XML value
    io:println(x1/*);

    // Function invocations
    x = add(1, 2);
    io:println(multiply(2, 4));
    // Invocation providing value for the defaultable parameter
    io:println(multiply(3, 4, true));
    // Invocation with values to a rest parameter (multi-valued)
    io:println(addAll(1, 2, 3));
    io:println(addAll(1, 2, 3, 4, 5));

    // Function pointers
    (function (int, int) returns int) op1 = getOperation("add");
    (function (int, int) returns int) op2 = getOperation("mod");
    io:println(op1(5, 10));
    io:println(op2(13, 10));

    // Closures
    (function (int x) returns int) add5 = getAdder(5);
    (function (int x) returns int) add10 = getAdder(10);
    io:println(add5(10));
    io:println(add10(10));

    int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8];
    // Functional iteration
    int[] evenNumbers = numbers.filter(function (int x) returns boolean { return x % 2 == 0; });

    // Union types - "input" is of type either string or byte[]
    string|byte[] uval = "XXX";

    // A type test expression ("uval is string") can be used to check the 
    // runtime type of a variable.
    if uval is string {
        // In the current scope, "uval" is a string value
        string data = "data:" + uval;
    } else {
        // Since the expression in the "if" statement ruled out that it's not a string,
        // the only type left is "byte[]"; so in the current scope, "uval" will always
        // be a "byte[]".
        int inputLength = uval.length();
    }

    // Error handling
    string input = io:readln("Enter number: ");
    int|error result = ints:fromString(input);
    if result is int {
        io:println("Number: ", result);
    } else {
        io:println("Invalid number: ", input);
    }

    // A check expression can be used to directly return the error from
    // the current function if its subexpression evaluated to an error
    // value in the runtime. 
    int number = check ints:fromString(input); 

    // Concurrent execution using workers in a function
    doWorkers();

    // Asynchronous execution with futures
    future&lt;int&gt; f10 = start fib(10);
    var webresult = clientEP-&gt;get("/");
    int fresult = wait f10;
    if webresult is http:Response {
        io:println(webresult.getTextPayload());
        io:println(fresult);
    }

    // Mapping types
    map&lt;int&gt; ageMap = {};
    ageMap["Peter"] = 25;
    ageMap["John"] = 30;

    int? agePeter = ageMap["Peter"]; // int? is the union type int|() - int or nill
    if agePeter is int {
        io:println("Peter's age is ", agePeter);
    } else {
        io:println("Peter's age is not found");
    }

    Person person1 = { id: "p1", name : "Anne", age: 28, country: "Sri Lanka" };
    Scores score1 = { physics : 80, mathematics: 95 };
    score1["chemistry"] = 75;
    io:println(score1["chemistry"]);

    Student student1 = { id: "s1", name: "Jack", age: 25, country: "Japan" };
    student1.college = "Stanford";
    string? jacksCollege = student1?.college; // optional field access
    if jacksCollege is string {
        io:println("Jack's college is ", jacksCollege);
    }

    // Due to the structural type system, "student1" can be assigned to "person2",
    // since the student1's structure is compatible with person2's,
    // where we can say, a "Student" is a "Person" as well. 
    Person person2 = student1;

    map&lt;int&gt; grades = {"Jack": 95, "Anne": 90, "John": 80, "Bill": 55};
    Person px1 = {id: "px1", name: "Jack", age: 30, country: "Canada"};
    Person px2 = {id: "px2", name: "John", age: 25};
    Person px3 = {id: "px3", name: "Anne", age: 17, country: "UK"};
    Person px4 = {id: "px4", name: "Bill", age: 15, country: "USA"};
    Person[] persons = [];
    persons.push(px1);
    persons.push(px2);
    persons.push(px3);
    persons.push(px4);

    // Query expressions used to execute complex queries for list data
    Result[] results = from var person in persons
                       let int lgrade = (grades[person.name] ?: 0)
                       where lgrade &gt; 75 
                           let string targetCollege = "Stanford"
                           select { 
                               name: person.name, 
                               college: targetCollege, 
                               grade: lgrade 
                           };

    // Compile-time taint checking for handling untrusted data
    string s1 = "abc";
    mySecureFunction(s1);
    // Explicitely make "s2" a tainted value. External input to a Ballerina
    // program such as command-line arguments and network input are by-default
    // marked as tainted data.
    string s2 = &lt;@tainted&gt; s1;
    // "s2x" is now a tainted value, since its value is derived using a 
    // tainted value (s1).
    string s2x = s2 + "abc";
    // The following line uncommented will result in a compilation error,
    // since we are passing a tainted value (s2x) to a function which 
    // exepects an untainted value.
    // mySecureFunction(s2x);

    // Instantiating objects
    Employee emp1 = new("E0001", "Jack Smith", "Sales", 2009);
    io:println("The company service duration of ", emp1.name, 
               " is ", emp1.serviceDuration());

    // Supported operations can be executed in a transaction by enclosing the actions
    // in a "transaction" block. 
    transaction {
        // Executes the below database operations in a single local transactions
        var r1 = accountsDB-&gt;update("UPDATE Employee SET balance = balance + ? WHERE id = ?", 5500.0, "ID001");
        var r2 = accountsDB-&gt;update("UPDATE Employee SET balance = balance + ? WHERE id = ?", 5500.0, "ID001");
    }
}

// An object is a behavioural type, which encapsulates both data and functionality.
type Employee object {

    // Private fields are only visible within the object and its methods
    private string empId;
    // Public fields can be accessed by anyone
    public string name;
    public string department;
    // The default qualifier is a "protected" field, 
    // which are accessible only within the module.
    int yearJoined;           

    // The object initialization function; automatically called when an object is instantiated.
    public function __init(string empId, string name, string department, int yearJoined) {
        self.empId = empId;
        self.name = name;
        self.department = department;
        self.yearJoined = yearJoined;        
    }

    // An object method
    public function serviceDuration() returns int {
        time:Time ct = time:currentTime();
        return time:getYear(ct) - self.yearJoined;
    }

};

// Student is a subtype of Person
type Student record {
    string id;
    string name;
    int age;
    string college?;
    string country;
};

type Scores record {
    int physics;
    int mathematics;
};

type Result record {
    string name;
    string college;
    int grade;
};

public function getOperation(string op) returns (function (int, int) returns int) {
    if op == "add" {
        return add;
    } else if op == "mod" {
        return function (int a, int b) returns int { // anonymous function
            return a % b;
        };
    } else {
        return (x, y) =&gt; 0; // single expression anonymous no-op function 
    }
}

// Two required parameters
public function add(int a, int b) returns int {
    return a + b;
}

// 'log' is a defaultable parameter
public function multiply(int a, int b, boolean log = false) returns int {
    if log {
        io:println("Multiplying ", a, " with ", b);
    }
    return a * b;
}

// 'numbers' is a rest parameter - it can have multiple values, 
// similar to an array.
public function addAll(int... numbers) returns int {
    int result = 0;
    foreach int number in numbers {
        result += number;
    }
    return result;
}

public function getAdder(int n) returns (function (int x) returns int) {
    return function (int x) returns int { // returns closure
        return x + n;
    };
}

function fib(int n) returns int {
    if n &lt;= 2 {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}

// The code in worker blocks "w1" and "w2" are executed concurrency 
// when this function is invoked. The "wait" expressions waits for
// the given workers to finish to retrieve their results.
public function doWorkers() {
    worker w1 returns int {
        int j = 10;
        j -&gt; w2;
        int b;
        b = &lt;- w2;
        return b * b;
    }
    worker w2 returns int {
        int a;
        a = &lt;- w1;
        a * 2 -&gt; w1;
        return a + 2;
    }
    record {int w1; int w2;} x = wait {w1, w2};
    io:println(x);
}

// A function which takes in only an untainted string value.
public function mySecureFunction(@untainted string input) {
    io:println(input);
}
</code></pre>
<p>BrainFuck:</p>
<pre><code class="lang-plaintext">Any character not "&gt;&lt;+-.,[]" (excluding quotation marks) is ignored.

Brainfuck is represented by an array with 30,000 cells initialized to zero
and a data pointer pointing at the current cell.

There are eight commands:
+ : Increments the value at the current cell by one.
- : Decrements the value at the current cell by one.
&gt; : Moves the data pointer to the next cell (cell on the right).
&lt; : Moves the data pointer to the previous cell (cell on the left).
. : Prints the ASCII value at the current cell (i.e. 65 = 'A').
, : Reads a single input character into the current cell.
[ : If the value at the current cell is zero, skips to the corresponding ] .
    Otherwise, move to the next instruction.
] : If the value at the current cell is zero, move to the next instruction.
    Otherwise, move backwards in the instructions to the corresponding [ .

[ and ] form a while loop. Obviously, they must be balanced.

Let's look at some basic brainfuck programs.

++++++ [ &gt; ++++++++++ &lt; - ] &gt; +++++ .

This program prints out the letter 'A'. First, it increments cell #1 to 6.
Cell #1 will be used for looping. Then, it enters the loop ([) and moves
to cell #2. It increments cell #2 10 times, moves back to cell #1, and
decrements cell #1. This loop happens 6 times (it takes 6 decrements for
cell #1 to reach 0, at which point it skips to the corresponding ] and
continues on).

At this point, we're on cell #1, which has a value of 0, while cell #2 has a
value of 60. We move on cell #2, increment 5 times, for a value of 65, and then
print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal.


, [ &gt; + &lt; - ] &gt; .

This program reads a character from the user input and copies the character into
cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2,
move back to cell #1, and decrement the value at cell #1. This continues on
until cell #1 is 0, and cell #2 holds cell #1's old value. Because we're on
cell #1 at the end of the loop, move to cell #2, and then print out the value
in ASCII.

Also keep in mind that the spaces are purely for readability purposes. You
could just as easily write it as:

,[&gt;+&lt;-]&gt;.

Try and figure out what this program does:

,&gt;,&lt; [ &gt; [ &gt;+ &gt;+ &lt;&lt; -] &gt;&gt; [- &lt;&lt; + &gt;&gt;] &lt;&lt;&lt; -] &gt;&gt;

This program takes two numbers for input, and multiplies them.

The gist is it first reads in two inputs. Then it starts the outer loop,
conditioned on cell #1. Then it moves to cell #2, and starts the inner
loop conditioned on cell #2, incrementing cell #3. However, there comes a
problem: At the end of the inner loop, cell #2 is zero. In that case,
inner loop won't work anymore since next time. To solve this problem,
we also increment cell #4, and then recopy cell #4 into cell #2.
Then cell #3 is the result.
</code></pre>
<p>BQN:</p>
<pre><code class="lang-plaintext"># This is a comment.
# The characters ',' and `⋄` are statement separators.

##################
# Main datatypes #
##################

# Numbers
1,2,3,4
¯1,¯2,¯3  # Negative numbers are written with a high minus
π,∞,¯π,¯∞ # Pi and Infinity are defined constants
1_234_456 # You can add underscores in between numbers
          # This does not change their value
1.3E4     # Scientific notation is supported

# Characters
'a','⥊'
'
'         # Yes, you can put *any* character in a character literal
@         # Null character ('\0' in C)
# Arrays
1‿2‿3       # Stranding, good for simple lists
⟨1,2,3⟩     # General list notation
⟨1‿2,2‿3⟩   # Both can be mixed
[1‿2,2‿3]   # Array notation
            # An array is multidimensional, as opposed to containing sublists.
            # It must be rectangular in shape (a grid structure rather than a tree structure)
[1‿2‿3,4‿5] # This is hence invalid
            # May be familiar coming from Numpy, MATLAB and similar languages.
"asdf"      # Character array (String)
"newline
separated"  # Allows newlines
"quo""tes"  # Escape a double quote by typing it twice
# Functions
1{𝕨+𝕩}3       # All functions are infix
              # 𝕨 is left argument, 𝕩 is right argument
{-𝕩}5         # 𝕨 can be omitted
1+3           # Same as the above
{𝕊𝕩}          # 𝕊 is a recursive call
              # (this function will loop forever)
{𝕨 𝕊 𝕩: 𝕨+𝕩}  # Functions can have headers (too many cases to discuss here)
              # Headers can define arity
{𝕊 a‿b: a}1‿2 # and also do basic pattern matching
              # (returns 1)

# Modifiers (higher order functions)
{𝕗,𝔽,𝕘,𝔾}      # 𝔽 and 𝔾 are the operands as callable functions
               # 𝕗 and 𝕘 are the operands as values
{𝔽𝕩}           # 1-modifiers use 𝔽/𝕗 ONLY
˜,˘,¨,⁼,⌜      # primitive 1-modifiers are superscripts
{𝕨𝔽𝔾𝕩}         # 2-modifiers MUST use both 𝔽/𝕗 and 𝔾/𝕘 in body or header
⊸,∘,○,⟜        # primitive 2-modifiers all have circles
+{⟨𝕗⟩}         # returns ⟨ + ⟩
1-{𝔽 𝕨 𝔾 𝕩 }×2 # returns ¯2 (operators are *also* infix)
               # (same as 1 -○× 2)

# Trains (Special form of function composition)
(+´÷≠) # Average (but how?)
# The above train is an F G H train, where
# (F G H) 𝕩 → (F 𝕩) G (H 𝕩)
# F ← +´, G ← ÷, H ← ≠
# In explicit form, this is
{(+´𝕩)÷≠𝕩}
# The second pattern is (f g) 𝕩 → f g 𝕩.
# longer trains are complex arrangements of these patterns, involving constants and Nothing (·).
# Read more about trains at https://mlochbaum.github.io/BQN/doc/train.html

# Evaluation order:
#  BQN evaluates functions right to left with no precedence rules governing *functions*. Functions are what
#  one would call operators in a mainstream language.
1÷2+3       # 1÷(2+3)   = 0.2
(1÷2)+3     # ((1÷2)+3) = 1.5

# Modifiers:
#  Modifiers are higher order functions, and bind tighter than functions. Modifiers execute left to right.
#  Modifiers can take non-function arguments e.g. Constant (`˙`)
+
1+˜2+○-∘×3  # 1(+˜)(2((+○-)∘×)3)

# Variables
#  Since the case of a variable matters to determine what it means, BQN variables are *case insensitive*
#  The case that a variable is written in can change the way it is interpreted by BQN.
#  Eg. `F` refers to a value as a callable function, whereas `f` refers to the same variable as just a value.
#  Variable assignment is done with `←`. Variables have naming conventions based on their value:
subject ← 1‿2‿3        # Arrays, single values, namespaces come under this
                       # name must start with with a lowercase letter
Function      ← {𝕨+𝕩}  # Primitive and user defined functions come under this, both monadic and dyadic
                       # Starts with an uppercase letter
_1modifier    ← {𝕨𝔽𝕩}  # Starts with an underscore
_2modifier_   ← {𝔽𝕨𝔾𝕩} # Starts and ends with an underscore
# Variable modification is done with `↩`. An existing name cannot be reassigned with `←`.
Func ↩ {"Hello"∾𝕩}
array_or_atom +↩ 2    # You can use a dyadic function for modification
                      #≡ 3‿4‿5
array_or_atom -↩      # Or a monadic function.
                      #≡ ¯3‿¯4‿¯5
#  Due to all functions being infix, you can use your own functions for modification as well:
array_or_atom {2⋆𝕩}↩  #≡ ⟨ 0.125, 0.0625, 0.03125 ⟩

##################
# BQN Primitives #
##################
# All of BQN's base primitives are a single character long. Refer to https://mlochbaum.github.io/BQN/help/index.html for
# examples.
# Here we will look at a few primitives from each section. You will want to consult the docs for detailed explanations.

# Primitive Functions
#  All BQN functions are variadic, and can take one or two arguments. The base functions have both monadic and dyadic overloads.
#  Usually the two overloads for a function are related.

## Arithmetic Functions
+, -, ×, ÷ # Add, Subtract, Signum/Multiply, Reciprocal/Divide , '*' does NOT do multiplication
           # ⌊∘÷ does floor division
√, ⋆       # Square root/Nth root, e^x/Power
#   All Arithmetic functions vectorize:
1 + 2‿3‿4     #≡ 3‿4‿5
1‿2‿3 + 2‿3‿4 #≡ 3‿5‿7
#   Character arithmetic(+ and - only):
"abc"+3       #≡ "def"
'a'-'d'       #≡ ¯3

## Logic Functions
∧, ∨, ¬       # For Booleans, return 1 or 0
≤, &lt;, &gt;, ≥, = # Vectorizing comparisons
≡, ≢          # Nonvectorizing comparisons

## Array manipulation Functions
↕             # Make a range
∾, ≍, ⋈       # Joining arrays together
a←1‿2‿3,b←4‿5 # Let us take a and b.
a∾b           #≡ 1‿2‿3‿4‿5
a≍b           #  Same as previous, since a and b are not multidimensional
              #  Adds an extra dimension, similar to a ⋈ for multidimensional arrays.
a⋈b           #≡ ⟨1‿2‿3, 4‿5⟩
⊑, ⊏          # Indexing
1⊑1‿2‿3       #≡ 2 (BQN is 0-indexed)
1‿2⊏1‿2‿3     #≡ 2‿3 (for multiple indices)
↑, ↓          # Getting a prefix, suffix of an array.
              # together they can be used for slicing
⥊             # Reshape/repeat items to create a new array

# Primitive 1-Modifiers
## Looping combinators
¨, ˘, ⌜ # Mapping/Zipping
´, ˝    # Fold from right
`       # Scan from left

## General combinators
˜       # duplicate argument/swap args - Very useful!
˙       # Create constant function
1 -˜ 2  #≡ 2 - 1
+˜ 2    #≡ 2 + 2

# Primitive 2-modifiers
## Control Flow
◶       # Choose from a list of funcs
⍟       # Repeat n times

## General Combinators
⊸, ⟜    # hook, hookf
∘, ○    # simple function composition

##########
# Blocks #
##########
# Code delimited by {}
# Lexically scoped
# For more info: https://mlochbaum.github.io/BQN/doc/block.html
# Can have headers, which are ways to explicitly define what a block should be.
# A block without headers is automatically inferred from its special variables (𝕨, 𝕩, ...).

# Function blocks
# Implicit variables(Capitals are functions):
#  - 𝕨, 𝕎 left argument
#  - 𝕩, 𝕏 right argument
#  - 𝕤, 𝕊 represent the block itself
#   Optional: one or more headers that trigger based on
#   - pattern match (':') o
#   - condition ('?') (similar to if-then-else)

{ # A factorial using headers:
  𝕊 0: 1;
  𝕊 𝕩: 𝕩×𝕊 𝕩-1
}
{ # Factorial with predicates
  𝕩&lt;2 ? 1; # Similar to an if-else pattern.
  𝕩×𝕊 𝕩-1
}

# Modifier blocks
# create 1-modifiers and 2-modifiers, which have separate types
# Implicit variables(Capitals are functions):
#  - has 𝕨 and 𝕩 if needed
#  - 𝕗, 𝔽 left operand
#  - 𝕘, 𝔾 right operand (only in 2-modifiers)
#  - 𝕣 represents the block itself* (requires underscores as per convention)
# Same header rules as functions.
{ 𝕨=0 ? 𝔽 𝕩; 𝔾 𝕩 } # execute 𝔽 or 𝔾 based on whether left argument is 0.

# Namespace blocks
# Create immutable namespaces with fields
# Require exports (`⇐`) for accessible fields.
# Use '.' for field access
n←{
  A←+
  b⇐4
}
n.b #≡ 4
n.a # ERROR

# Immediate Blocks
#  No arguments taken
#  Run the code inside and return the last statement
#  Often responsible for strange errors.
#  Can be mistaken for other blocks easily
#  Good for avoiding scoping issues
{
  1‿2‿3
}
{+} # Trick for returning a function as a value
####################
# Basic constructs #
####################
# Functional programming
# `¨` is used for mapping, as discussed before:
{𝕩∾2}¨1‿2‿3 #≡ ⟨1‿2,2‿2,3‿2⟩
# ⋈¨ is a plain zip, which produces pairs.
# `¨` acts as a zipWith when used with two arguments:
1‿2‿3 {⟨𝕩+2,2⥊𝕨⟩} 4‿5‿6 #≡ ⟨⟨6,1‿1⟩,⟨7,2‿2⟩,⟨8,3‿3⟩⟩
# `/` is replicate, which serves several purposes *including* filtering.
# elements in 𝕩 are repeated by the corresponding number in 𝕨.
1‿2‿3‿0/4‿5‿6‿7 #≡ 4‿5‿5‿6‿6‿6
# a simple filter idiom is F⊸/:
{2|𝕩}⊸/67‿42‿83 # keep the odd elements
                #≡ 67‿83

# Conditionals
# There are two main ways to define a conditional.
## Predicate headers
{
  𝕩 &gt; 2:  "greater than 2";
  𝕩 &lt; 2: "lesser than 2";
  "equal to 2"
}

## Choose (function-based)
#  - 2-modifier
#  - 𝔾: list of functions that serve as bodies
#  - 𝔽: condition function that specifies which function from 𝔾 to select
#  The same conditional as above would be:
{⊑/⟨𝕩&gt;2, 𝕩&lt;2, 𝕩=2⟩}◶⟨
  {𝕊: "greater than 2"}
  {𝕊: "lesser than 2"}
  {𝕊: "equal to 2"}
⟩

## Some helpers for conditionals
If      ← {𝕏⍟𝕎@}´                 # Used as If ⟨Condition, Block⟩
IfElse  ← {c‿T‿F: c◶F‿T@}         # Used as IfElse ⟨Condition, Block, ElseBlock⟩

# Looping
# The primary form of unbounded looping is recursion (performed with 𝕊).
# BQN does not eliminate tail calls, but the while idiom can be used to work around this:
While ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´  # While 1‿{... to run forever
DoWhile ← {𝕏@ ⋄ While 𝕨‿𝕩}´
# A For loop can be done with ¨, functions need not be pure.
</code></pre>
<p>Chapel:</p>
<pre><code class="lang-plaintext">/*
   Learn Chapel in Y Minutes

   This primer will go over basic syntax and concepts in Chapel.
   Last sync with official page: Sun, 08 Mar 2020 08:05:53 +0000
*/

// Comments are C-family style

// one line comment
/*
    multi-line comment
*/

/*
Basic printing
*/

write("Hello, ");
writeln("World!");

// ``write`` and ``writeln`` can take a list of things to print.
// Each thing is printed right next to the others, so include your spacing!
writeln("There are ", 3, " commas (\",\") in this line of code");

// Different output channels:
use IO; // Required for accessing the alternative output channels

stdout.writeln("This goes to standard output, just like plain writeln() does");
stderr.writeln("This goes to standard error");

/*
Variables
*/

// Variables don't have to be explicitly typed as long as
// the compiler can figure out the type that it will hold.
// 10 is an ``int``, so ``myVar`` is implicitly an ``int``
var myVar = 10;
myVar = -10;
var mySecondVar = myVar;
// ``var anError;`` would be a compile-time error.

// We can (and should) explicitly type things.
var myThirdVar: real;
var myFourthVar: real = -1.234;
myThirdVar = myFourthVar;

/*
Types
*/

// There are a number of basic types.
var myInt: int = -1000; // Signed ints
var myUint: uint = 1234; // Unsigned ints
var myReal: real = 9.876; // Floating point numbers
var myImag: imag = 5.0i; // Imaginary numbers
var myCplx: complex = 10 + 9i; // Complex numbers
myCplx = myInt + myImag; // Another way to form complex numbers
var myBool: bool = false; // Booleans
var myStr: string = "Some string..."; // Strings
var singleQuoteStr = 'Another string...'; // String literal with single quotes

// Some types can have sizes.
var my8Int: int(8) = 10; // 8 bit (one byte) sized int;
var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real

// Typecasting.
var intFromReal = myReal : int;
var intFromReal2: int = myReal : int;

// Type aliasing.
type chroma = int;        // Type of a single hue
type RGBColor = 3*chroma; // Type representing a full color
var black: RGBColor = (0,0,0);
var white: RGBColor = (255, 255, 255);

/*
Constants and Parameters
*/

// A ``const`` is a constant, and cannot be changed after set in runtime.
const almostPi: real = 22.0/7.0;

// A ``param`` is a constant whose value must be known statically at
// compile-time.
param compileTimeConst: int = 16;

// The ``config`` modifier allows values to be set at the command line.
// Set with ``--varCmdLineArg=Value`` or ``--varCmdLineArg Value`` at runtime.
config var varCmdLineArg: int = -123;
config const constCmdLineArg: int = 777;

// ``config param`` can be set at compile-time.
// Set with ``--set paramCmdLineArg=value`` at compile-time.
config param paramCmdLineArg: bool = false;
writeln(varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg);

/*
References
*/

// ``ref`` operates much like a reference in C++. In Chapel, a ``ref`` cannot
// be made to alias a variable other than the variable it is initialized with.
// Here, ``refToActual`` refers to ``actual``.
var actual = 10;
ref refToActual = actual; 
writeln(actual, " == ", refToActual); // prints the same value
actual = -123; // modify actual (which refToActual refers to)
writeln(actual, " == ", refToActual); // prints the same value
refToActual = 99999999; // modify what refToActual refers to (which is actual)
writeln(actual, " == ", refToActual); // prints the same value

/*
Operators
*/

// Math operators:
var a: int, thisInt = 1234, thatInt = 5678;
a = thisInt + thatInt;  // Addition
a = thisInt * thatInt;  // Multiplication
a = thisInt - thatInt;  // Subtraction
a = thisInt / thatInt;  // Division
a = thisInt ** thatInt; // Exponentiation
a = thisInt % thatInt;  // Remainder (modulo)

// Logical operators:
var b: bool, thisBool = false, thatBool = true;
b = thisBool &amp;&amp; thatBool; // Logical and
b = thisBool || thatBool; // Logical or
b = !thisBool;            // Logical negation

// Relational operators:
b = thisInt &gt; thatInt;           // Greater-than
b = thisInt &gt;= thatInt;          // Greater-than-or-equal-to
b = thisInt &lt; a &amp;&amp; a &lt;= thatInt; // Less-than, and, less-than-or-equal-to
b = thisInt != thatInt;          // Not-equal-to
b = thisInt == thatInt;          // Equal-to

// Bitwise operators:
a = thisInt &lt;&lt; 10;     // Left-bit-shift by 10 bits;
a = thatInt &gt;&gt; 5;      // Right-bit-shift by 5 bits;
a = ~thisInt;          // Bitwise-negation
a = thisInt ^ thatInt; // Bitwise exclusive-or

// Compound assignment operators:
a += thisInt;          // Addition-equals (a = a + thisInt;)
a *= thatInt;          // Times-equals (a = a * thatInt;)
b &amp;&amp;= thatBool;        // Logical-and-equals (b = b &amp;&amp; thatBool;)
a &lt;&lt;= 3;               // Left-bit-shift-equals (a = a &lt;&lt; 10;)

// Unlike other C family languages, there are no
// pre/post-increment/decrement operators, such as:
//
// ``++j``, ``--j``, ``j++``, ``j--``

// Swap operator:
var old_this = thisInt;
var old_that = thatInt;
thisInt &lt;=&gt; thatInt; // Swap the values of thisInt and thatInt
writeln((old_this == thatInt) &amp;&amp; (old_that == thisInt));

// Operator overloads can also be defined, as we'll see with procedures.

/*
Tuples
*/

// Tuples can be of the same type or different types.
var sameTup: 2*int = (10, -1);
var sameTup2 = (11, -6);
var diffTup: (int,real,complex) = (5, 1.928, myCplx);
var diffTupe2 = (7, 5.64, 6.0+1.5i);

// Tuples can be accessed using square brackets or parentheses, and are
// 1-indexed.
writeln("(", sameTup[1], ",", sameTup(2), ")");
writeln(diffTup);

// Tuples can also be written into.
diffTup(1) = -1;

// Tuple values can be expanded into their own variables.
var (tupInt, tupReal, tupCplx) = diffTup;
writeln(diffTup == (tupInt, tupReal, tupCplx));

// They are also useful for writing a list of variables, as is common in debugging.
writeln((a,b,thisInt,thatInt,thisBool,thatBool));

/*
Control Flow
*/

// ``if`` - ``then`` - ``else`` works just like any other C-family language.
if 10 &lt; 100 then
  writeln("All is well");

if -1 &lt; 1 then
  writeln("Continuing to believe reality");
else
  writeln("Send mathematician, something's wrong");

// You can use parentheses if you prefer.
if (10 &gt; 100) {
  writeln("Universe broken. Please reboot universe.");
}

if a % 2 == 0 {
  writeln(a, " is even.");
} else {
  writeln(a, " is odd.");
}

if a % 3 == 0 {
  writeln(a, " is even divisible by 3.");
} else if a % 3 == 1 {
  writeln(a, " is divided by 3 with a remainder of 1.");
} else {
  writeln(b, " is divided by 3 with a remainder of 2.");
}

// Ternary: ``if`` - ``then`` - ``else`` in a statement.
var maximum = if thisInt &lt; thatInt then thatInt else thisInt;

// ``select`` statements are much like switch statements in other languages.
// However, ``select`` statements don't cascade like in C or Java.
var inputOption = "anOption";
select inputOption {
  when "anOption" do writeln("Chose 'anOption'");
  when "otherOption" {
    writeln("Chose 'otherOption'");
    writeln("Which has a body");
  }
  otherwise {
    writeln("Any other Input");
    writeln("the otherwise case doesn't need a do if the body is one line");
  }
}

// ``while`` and ``do``-``while`` loops also behave like their C counterparts.
var j: int = 1;
var jSum: int = 0;
while (j &lt;= 1000) {
  jSum += j;
  j += 1;
}
writeln(jSum);

do {
  jSum += j;
  j += 1;
} while (j &lt;= 10000);
writeln(jSum);

// ``for`` loops are much like those in python in that they iterate over a
// range. Ranges (like the ``1..10`` expression below) are a first-class object
// in Chapel, and as such can be stored in variables.
for i in 1..10 do write(i, ", ");
writeln();

var iSum: int = 0;
for i in 1..1000 {
  iSum += i;
}
writeln(iSum);

for x in 1..10 {
  for y in 1..10 {
    write((x,y), "\t");
  }
  writeln();
}

/*
Ranges and Domains
*/

// For-loops and arrays both use ranges and domains to define an index set that
// can be iterated over. Ranges are single dimensional integer indices, while
// domains can be multi-dimensional and represent indices of different types.

// They are first-class citizen types, and can be assigned into variables.
var range1to10: range = 1..10;  // 1, 2, 3, ..., 10
var range2to11 = 2..11; // 2, 3, 4, ..., 11
var rangeThisToThat: range = thisInt..thatInt; // using variables
var rangeEmpty: range = 100..-100; // this is valid but contains no indices

// Ranges can be unbounded.
var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ...
var rangeNegInfTo1 = ..1; // ..., -4, -3, -2, -1, 0, 1

// Ranges can be strided (and reversed) using the ``by`` operator.
var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10
var reverse2to10by2 = 2..10 by -2; // 10, 8, 6, 4, 2

var trapRange = 10..1 by -1; // Do not be fooled, this is still an empty range
writeln("Size of range '", trapRange, "' = ", trapRange.size);

// Note: ``range(boundedType= ...)`` and ``range(stridable= ...)`` are only
// necessary if we explicitly type the variable.

// The end point of a range can be computed by specifying the total size
// of the range using the count (``#``) operator.
var rangeCount: range = -5..#12; // range from -5 to 6

// Operators can be mixed.
var rangeCountBy: range(stridable=true) = -5..#12 by 2; // -5, -3, -1, 1, 3, 5
writeln(rangeCountBy);

// Properties of the range can be queried.
// In this example, printing the first index, last index, number of indices,
// stride, and if 2 is include in the range.
writeln((rangeCountBy.first, rangeCountBy.last, rangeCountBy.size,
           rangeCountBy.stride, rangeCountBy.contains(2)));

for i in rangeCountBy {
  write(i, if i == rangeCountBy.last then "\n" else ", ");
}

// Rectangular domains are defined using the same range syntax,
// but they are required to be bounded (unlike ranges).
var domain1to10: domain(1) = {1..10};        // 1D domain from 1..10;
var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges
var thirdDim: range = 1..16;
var threeDims: domain(3) = {thirdDim, 1..10, 5..10}; // using a range variable

// Domains can also be resized
var resizedDom = {1..10};
writeln("before, resizedDom = ", resizedDom);
resizedDom = {-10..#10};
writeln("after, resizedDom = ", resizedDom);

// Indices can be iterated over as tuples.
for idx in twoDimensions do
  write(idx, ", ");
writeln();

// These tuples can also be destructured.
for (x,y) in twoDimensions {
  write("(", x, ", ", y, ")", ", ");
}
writeln();

// Associative domains act like sets.
var stringSet: domain(string); // empty set of strings
stringSet += "a";
stringSet += "b";
stringSet += "c";
stringSet += "a"; // Redundant add "a"
stringSet -= "c"; // Remove "c"
writeln(stringSet.sorted());

// Associative domains can also have a literal syntax
var intSet = {1, 2, 4, 5, 100};

// Both ranges and domains can be sliced to produce a range or domain with the
// intersection of indices.
var rangeA = 1.. ; // range from 1 to infinity
var rangeB =  ..5; // range from negative infinity to 5
var rangeC = rangeA[rangeB]; // resulting range is 1..5
writeln((rangeA, rangeB, rangeC));

var domainA = {1..10, 5..20};
var domainB = {-5..5, 1..10};
var domainC = domainA[domainB];
writeln((domainA, domainB, domainC));

/*
Arrays
*/

// Arrays are similar to those of other languages.
// Their sizes are defined using domains that represent their indices.
var intArray: [1..10] int;
var intArray2: [{1..10}] int; // equivalent

// They can be accessed using either brackets or parentheses
for i in 1..10 do
  intArray[i] = -i;
writeln(intArray);

// We cannot access ``intArray[0]`` because it exists outside
// of the index set, ``{1..10}``, we defined it to have.
// ``intArray[11]`` is illegal for the same reason.
var realDomain: domain(2) = {1..5,1..7};
var realArray: [realDomain] real;
var realArray2: [1..5,1..7] real;   // equivalent
var realArray3: [{1..5,1..7}] real; // equivalent

for i in 1..5 {
  for j in realDomain.dim(2) {   // Only use the 2nd dimension of the domain
    realArray[i,j] = -1.61803 * i + 0.5 * j;  // Access using index list
    var idx: 2*int = (i,j);                   // Note: 'index' is a keyword
    realArray[idx] = - realArray[(i,j)];      // Index using tuples
  }
}

// Arrays have domains as members, and can be iterated over as normal.
for idx in realArray.domain {  // Again, idx is a 2*int tuple
  realArray[idx] = 1 / realArray[idx[1], idx[2]]; // Access by tuple and list
}

writeln(realArray);

// The values of an array can also be iterated directly.
var rSum: real = 0;
for value in realArray {
  rSum += value; // Read a value
  value = rSum;  // Write a value
}
writeln(rSum, "\n", realArray);

// Associative arrays (dictionaries) can be created using associative domains.
var dictDomain: domain(string) = { "one", "two", "three"};
var dict: [dictDomain] int = ["one" =&gt; 1, "two" =&gt; 2, "three" =&gt; 3];

for key in dictDomain.sorted() do
  writeln(dict[key]);

// Arrays can be assigned to each other in a few different ways.
// These arrays will be used in the example.
var thisArray : [0..5] int = [0,1,2,3,4,5];
var thatArray : [0..5] int;

// First, simply assign one to the other. This copies ``thisArray`` into
// ``thatArray``, instead of just creating a reference. Therefore, modifying
// ``thisArray`` does not also modify ``thatArray``.

thatArray = thisArray;
thatArray[1] = -1;
writeln((thisArray, thatArray));

// Assign a slice from one array to a slice (of the same size) in the other.
thatArray[4..5] = thisArray[1..2];
writeln((thisArray, thatArray));

// Operations can also be promoted to work on arrays. 'thisPlusThat' is also
// an array.
var thisPlusThat = thisArray + thatArray;
writeln(thisPlusThat);

// Moving on, arrays and loops can also be expressions, where the loop
// body's expression is the result of each iteration.
var arrayFromLoop = for i in 1..10 do i;
writeln(arrayFromLoop);

// An expression can result in nothing, such as when filtering with an if-expression.
var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i;

writeln(arrayFromLoop);

// Array expressions can also be written with a bracket notation.
// Note: this syntax uses the ``forall`` parallel concept discussed later.
var evensOrFivesAgain = [i in 1..10] if (i % 2 == 0 || i % 5 == 0) then i;

// They can also be written over the values of the array.
arrayFromLoop = [value in arrayFromLoop] value + 1;


/*
Procedures
*/

// Chapel procedures have similar syntax functions in other languages. 
proc fibonacci(n : int) : int {
  if n &lt;= 1 then return n;
  return fibonacci(n-1) + fibonacci(n-2);
}

// Input parameters can be untyped to create a generic procedure.
proc doublePrint(thing): void {
  write(thing, " ", thing, "\n");
}

// The return type can be inferred, as long as the compiler can figure it out.
proc addThree(n) {
  return n + 3;
}

doublePrint(addThree(fibonacci(20)));

// It is also possible to take a variable number of parameters.
proc maxOf(x ...?k) {
  // x refers to a tuple of one type, with k elements
  var maximum = x[1];
  for i in 2..k do maximum = if maximum &lt; x[i] then x[i] else maximum;
  return maximum;
}
writeln(maxOf(1, -10, 189, -9071982, 5, 17, 20001, 42));

// Procedures can have default parameter values, and
// the parameters can be named in the call, even out of order.
proc defaultsProc(x: int, y: real = 1.2634): (int,real) {
  return (x,y);
}

writeln(defaultsProc(10));
writeln(defaultsProc(x=11));
writeln(defaultsProc(x=12, y=5.432));
writeln(defaultsProc(y=9.876, x=13));

// The ``?`` operator is called the query operator, and is used to take
// undetermined values like tuple or array sizes and generic types.
// For example, taking arrays as parameters. The query operator is used to
// determine the domain of ``A``. This is useful for defining the return type,
// though it's not required.
proc invertArray(A: [?D] int): [D] int{
  for a in A do a = -a;
  return A;
}

writeln(invertArray(intArray));

// We can query the type of arguments to generic procedures.
// Here we define a procedure that takes two arguments of
// the same type, yet we don't define what that type is.
proc genericProc(arg1 : ?valueType, arg2 : valueType): void {
  select(valueType) {
    when int do writeln(arg1, " and ", arg2, " are ints");
    when real do writeln(arg1, " and ", arg2, " are reals");
    otherwise writeln(arg1, " and ", arg2, " are somethings!");
  }
}

genericProc(1, 2);
genericProc(1.2, 2.3);
genericProc(1.0+2.0i, 3.0+4.0i);

// We can also enforce a form of polymorphism with the ``where`` clause
// This allows the compiler to decide which function to use.
// Note: That means that all information needs to be known at compile-time.
// The param modifier on the arg is used to enforce this constraint.
proc whereProc(param N : int): void
 where (N &gt; 0) {
  writeln("N is greater than 0");
}

proc whereProc(param N : int): void
 where (N &lt; 0) {
  writeln("N is less than 0");
}

whereProc(10);
whereProc(-1);

// ``whereProc(0)`` would result in a compiler error because there
// are no functions that satisfy the ``where`` clause's condition.
// We could have defined a ``whereProc`` without a ``where`` clause
// that would then have served as a catch all for all the other cases
// (of which there is only one).

// ``where`` clauses can also be used to constrain based on argument type.
proc whereType(x: ?t) where t == int {
  writeln("Inside 'int' version of 'whereType': ", x);
}

proc whereType(x: ?t) {
  writeln("Inside general version of 'whereType': ", x);
}

whereType(42);
whereType("hello");

/*
Intents
*/

/* Intent modifiers on the arguments convey how those arguments are passed to the procedure.

     * in: copy arg in, but not out
     * out: copy arg out, but not in
     * inout: copy arg in, copy arg out
     * ref: pass arg by reference
*/
proc intentsProc(in inarg, out outarg, inout inoutarg, ref refarg) {
  writeln("Inside Before: ", (inarg, outarg, inoutarg, refarg));
  inarg = inarg + 100;
  outarg = outarg + 100;
  inoutarg = inoutarg + 100;
  refarg = refarg + 100;
  writeln("Inside After: ", (inarg, outarg, inoutarg, refarg));
}

var inVar: int = 1;
var outVar: int = 2;
var inoutVar: int = 3;
var refVar: int = 4;
writeln("Outside Before: ", (inVar, outVar, inoutVar, refVar));
intentsProc(inVar, outVar, inoutVar, refVar);
writeln("Outside After: ", (inVar, outVar, inoutVar, refVar));

// Similarly, we can define intents on the return type.
// ``refElement`` returns a reference to an element of array.
// This makes more practical sense for class methods where references to
// elements in a data-structure are returned via a method or iterator.
proc refElement(array : [?D] ?T, idx) ref : T {
  return array[idx];
}

var myChangingArray : [1..5] int = [1,2,3,4,5];
writeln(myChangingArray);
ref refToElem = refElement(myChangingArray, 5); // store reference to element in ref variable
writeln(refToElem);
refToElem = -2; // modify reference which modifies actual value in array
writeln(refToElem);
writeln(myChangingArray);

/*
Operator Definitions
*/

// Chapel allows for operators to be overloaded.
// We can define the unary operators:
// ``+ - ! ~``
// and the binary operators:
// ``+ - * / % ** == &lt;= &gt;= &lt; &gt; &lt;&lt; &gt;&gt; &amp; | ˆ by``
// ``+= -= *= /= %= **= &amp;= |= ˆ= &lt;&lt;= &gt;&gt;= &lt;=&gt;``

// Boolean exclusive or operator.
proc ^(left : bool, right : bool): bool {
  return (left || right) &amp;&amp; !(left &amp;&amp; right);
}

writeln(true  ^ true);
writeln(false ^ true);
writeln(true  ^ false);
writeln(false ^ false);

// Define a ``*`` operator on any two types that returns a tuple of those types.
proc *(left : ?ltype, right : ?rtype): (ltype, rtype) {
  writeln("\tIn our '*' overload!");
  return (left, right);
}

writeln(1 * "a"); // Uses our ``*`` operator.
writeln(1 * 2);   // Uses the default ``*`` operator.

//  Note: You could break everything if you get careless with your overloads.
//  This here will break everything. Don't do it.

/* 

      proc +(left: int, right: int): int {
        return left - right;
      }
*/

/*
Iterators
*/

// Iterators are sisters to the procedure, and almost everything about
// procedures also applies to iterators. However, instead of returning a single
// value, iterators may yield multiple values to a loop.
//
// This is useful when a complicated set or order of iterations is needed, as
// it allows the code defining the iterations to be separate from the loop
// body.
iter oddsThenEvens(N: int): int {
  for i in 1..N by 2 do
    yield i; // yield values instead of returning.
  for i in 2..N by 2 do
    yield i;
}

for i in oddsThenEvens(10) do write(i, ", ");
writeln();

// Iterators can also yield conditionally, the result of which can be nothing
iter absolutelyNothing(N): int {
  for i in 1..N {
    if N &lt; i { // Always false
      yield i;     // Yield statement never happens
    }
  }
}

for i in absolutelyNothing(10) {
  writeln("Woa there! absolutelyNothing yielded ", i);
}

// We can zipper together two or more iterators (who have the same number
// of iterations) using ``zip()`` to create a single zipped iterator, where each
// iteration of the zipped iterator yields a tuple of one value yielded
// from each iterator.
for (positive, negative) in zip(1..5, -5..-1) do
  writeln((positive, negative));

// Zipper iteration is quite important in the assignment of arrays,
// slices of arrays, and array/loop expressions.
var fromThatArray : [1..#5] int = [1,2,3,4,5];
var toThisArray : [100..#5] int;

// Some zipper operations implement other operations.
// The first statement and the loop are equivalent.
toThisArray = fromThatArray;
for (i,j) in zip(toThisArray.domain, fromThatArray.domain) {
  toThisArray[i] = fromThatArray[j];
}

// These two chunks are also equivalent.
toThisArray = [j in -100..#5] j;
writeln(toThisArray);

for (i, j) in zip(toThisArray.domain, -100..#5) {
  toThisArray[i] = j;
}
writeln(toThisArray);

// This is very important in understanding why this statement exhibits a runtime error.

/* 
      var iterArray : [1..10] int = [i in 1..10] if (i % 2 == 1) then i;
*/

// Even though the domain of the array and the loop-expression are
// the same size, the body of the expression can be thought of as an iterator.
// Because iterators can yield nothing, that iterator yields a different number
// of things than the domain of the array or loop, which is not allowed.

/*
Classes
*/
// Classes are similar to those in C++ and Java, allocated on the heap.
class MyClass {

// Member variables
  var memberInt : int;
  var memberBool : bool = true;

// By default, any class that doesn't define an initializer gets a
// compiler-generated initializer, with one argument per field and
// the field's initial value as the argument's default value.
// Alternatively, the user can define initializers manually as shown
// in the following commented-out routine:
//
/*       // proc init(val : real) {
      //   this.memberInt = ceil(val): int;
      // }
*/

// Explicitly defined deinitializer.
// If we did not write one, we would get the compiler-generated deinitializer,
// which has an empty body.
  proc deinit() {
    writeln("MyClass deinitializer called ", (this.memberInt, this.memberBool));
  }

// Class methods.
  proc setMemberInt(val: int) {
    this.memberInt = val;
  }

  proc setMemberBool(val: bool) {
    this.memberBool = val;
  }

  proc getMemberInt(): int{
    return this.memberInt;
  }

  proc getMemberBool(): bool {
    return this.memberBool;
  }
} // end MyClass

// Call compiler-generated initializer, using default value for memberBool.
{
  var myObject = new owned MyClass(10);
      myObject = new owned MyClass(memberInt = 10); // Equivalent
  writeln(myObject.getMemberInt());

  // Same, but provide a memberBool value explicitly.
  var myDiffObject = new owned MyClass(-1, true);
      myDiffObject = new owned MyClass(memberInt = -1,
                                       memberBool = true); // Equivalent
  writeln(myDiffObject);

  // Similar, but rely on the default value of memberInt, passing in memberBool.
  var myThirdObject = new owned MyClass(memberBool = true);
  writeln(myThirdObject);

  // If the user-defined initializer above had been uncommented, we could
  // make the following calls:
  //
  /*         // var myOtherObject = new MyClass(1.95);
        //     myOtherObject = new MyClass(val = 1.95);
        // writeln(myOtherObject.getMemberInt());
  */

  // We can define an operator on our class as well, but
  // the definition has to be outside the class definition.
  proc +(A : MyClass, B : MyClass) : owned MyClass {
    return
      new owned MyClass(memberInt = A.getMemberInt() + B.getMemberInt(),
                        memberBool = A.getMemberBool() || B.getMemberBool());
  }

  var plusObject = myObject + myDiffObject;
  writeln(plusObject);

  // Destruction of an object: calls the deinit() routine and frees its memory.
  // ``unmanaged`` variables should have ``delete`` called on them.
  // ``owned`` variables are destroyed when they go out of scope.
}

// Classes can inherit from one or more parent classes
class MyChildClass : MyClass {
  var memberComplex: complex;
}

// Here's an example of generic classes.
class GenericClass {
  type classType;
  var classDomain: domain(1);
  var classArray: [classDomain] classType;

// Explicit initializer.
  proc init(type classType, elements : int) {
    this.classType = classType;
    this.classDomain = {1..elements};
    // all generic and const fields must be initialized in "phase 1" prior
    // to a call to the superclass initializer.
  }

// Copy-style initializer.
// Note: We include a type argument whose default is the type of the first
// argument.  This lets our initializer copy classes of different
// types and cast on the fly.
  proc init(other : GenericClass(?),
            type classType = other.classType) {
    this.classType = classType;
    this.classDomain = other.classDomain;
    this.classArray = for o in other do o: classType;  // copy and cast
  }

// Define bracket notation on a GenericClass
// object so it can behave like a normal array
// i.e. ``objVar[i]`` or ``objVar(i)``
  proc this(i : int) ref : classType {
    return this.classArray[i];
  }

// Define an implicit iterator for the class
// to yield values from the array to a loop
// i.e. ``for i in objVar do ...``
  iter these() ref : classType {
    for i in this.classDomain do
      yield this[i];
  }
} // end GenericClass

// Allocate an owned instance of our class
var realList = new owned GenericClass(real, 10);

// We can assign to the member array of the object using the bracket
// notation that we defined.
for i in realList.classDomain do realList[i] = i + 1.0;

// We can iterate over the values in our list with the iterator
// we defined.
for value in realList do write(value, ", ");
writeln();

// Make a copy of realList using the copy initializer.
var copyList = new owned GenericClass(realList);
for value in copyList do write(value, ", ");
writeln();

// Make a copy of realList and change the type, also using the copy initializer.
var copyNewTypeList = new owned GenericClass(realList, int);
for value in copyNewTypeList do write(value, ", ");
writeln();


/*
Modules
*/

// Modules are Chapel's way of managing name spaces.
// The files containing these modules do not need to be named after the modules
// (as in Java), but files implicitly name modules.
// For example, this file implicitly names the ``learnChapelInYMinutes`` module

module OurModule {

// We can use modules inside of other modules.
// Time is one of the standard modules.
  use Time;

// We'll use this procedure in the parallelism section.
  proc countdown(seconds: int) {
    for i in 1..seconds by -1 {
      writeln(i);
      sleep(1);
    }
  }

// It is possible to create arbitrarily deep module nests.
// i.e. submodules of OurModule
  module ChildModule {
    proc foo() {
      writeln("ChildModule.foo()");
    }
  }

  module SiblingModule {
    proc foo() {
      writeln("SiblingModule.foo()");
    }
  }
} // end OurModule

// Using ``OurModule`` also uses all the modules it uses.
// Since ``OurModule`` uses ``Time``, we also use ``Time``.
use OurModule;

// At this point we have not used ``ChildModule`` or ``SiblingModule`` so
// their symbols (i.e. ``foo``) are not available to us. However, the module
// names are available, and we can explicitly call ``foo()`` through them.
SiblingModule.foo();
OurModule.ChildModule.foo();

// Now we use ``ChildModule``, enabling unqualified calls.
use ChildModule;
foo();

/*
Parallelism
*/

// In other languages, parallelism is typically done with
// complicated libraries and strange class structure hierarchies.
// Chapel has it baked right into the language.

// We can declare a main procedure, but all the code above main still gets
// executed.
proc main() {

// A ``begin`` statement will spin the body of that statement off
// into one new task.
// A ``sync`` statement will ensure that the progress of the main
// task will not progress until the children have synced back up.

  sync {
    begin { // Start of new task's body
      var a = 0;
      for i in 1..1000 do a += 1;
      writeln("Done: ", a);
    } // End of new tasks body
    writeln("spun off a task!");
  }
  writeln("Back together");

  proc printFibb(n: int) {
    writeln("fibonacci(",n,") = ", fibonacci(n));
  }

// A ``cobegin`` statement will spin each statement of the body into one new
// task. Notice here that the prints from each statement may happen in any
// order.
  cobegin {
    printFibb(20); // new task
    printFibb(10); // new task
    printFibb(5);  // new task
    {
      // This is a nested statement body and thus is a single statement
      // to the parent statement, executed by a single task.
      writeln("this gets");
      writeln("executed as");
      writeln("a whole");
    }
  }

// A ``coforall`` loop will create a new task for EACH iteration.
// Again we see that prints happen in any order.
// NOTE: ``coforall`` should be used only for creating tasks!
// Using it to iterating over a structure is very a bad idea!
  var num_tasks = 10; // Number of tasks we want
  coforall taskID in 1..num_tasks {
    writeln("Hello from task# ", taskID);
  }

// ``forall`` loops are another parallel loop, but only create a smaller number
// of tasks, specifically ``--dataParTasksPerLocale=`` number of tasks.
  forall i in 1..100 {
    write(i, ", ");
  }
  writeln();

// Here we see that there are sections that are in order, followed by
// a section that would not follow (e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6,).
// This is because each task is taking on a chunk of the range 1..10
// (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens
// in parallel. Your results may depend on your machine and configuration

// For both the ``forall`` and ``coforall`` loops, the execution of the
// parent task will not continue until all the children sync up.

// ``forall`` loops are particularly useful for parallel iteration over arrays.
// Lets run an experiment to see how much faster a parallel loop is
  use Time; // Import the Time module to use Timer objects
  var timer: Timer;
  var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into

// Serial Experiment:
  timer.start(); // Start timer
  for (x,y) in myBigArray.domain { // Serial iteration
    myBigArray[x,y] = (x:real) / (y:real);
  }
  timer.stop(); // Stop timer
  writeln("Serial: ", timer.elapsed()); // Print elapsed time
  timer.clear(); // Clear timer for parallel loop

// Parallel Experiment:
  timer.start(); // start timer
  forall (x,y) in myBigArray.domain { // Parallel iteration
    myBigArray[x,y] = (x:real) / (y:real);
  }
  timer.stop(); // Stop timer
  writeln("Parallel: ", timer.elapsed()); // Print elapsed time
  timer.clear();

// You may have noticed that (depending on how many cores you have)
// the parallel loop went faster than the serial loop.

// The bracket style loop-expression described
// much earlier implicitly uses a ``forall`` loop.
  [val in myBigArray] val = 1 / val; // Parallel operation

// Atomic variables, common to many languages, are ones whose operations
// occur uninterrupted. Multiple threads can therefore modify atomic
// variables and can know that their values are safe.
// Chapel atomic variables can be of type ``bool``, ``int``,
// ``uint``, and ``real``.
  var uranium: atomic int;
  uranium.write(238);      // atomically write a variable
  writeln(uranium.read()); // atomically read a variable

// Atomic operations are described as functions, so you can define your own.
  uranium.sub(3); // atomically subtract a variable
  writeln(uranium.read());

  var replaceWith = 239;
  var was = uranium.exchange(replaceWith);
  writeln("uranium was ", was, " but is now ", replaceWith);

  var isEqualTo = 235;
  if uranium.compareAndSwap(isEqualTo, replaceWith) {
    writeln("uranium was equal to ", isEqualTo,
             " so replaced value with ", replaceWith);
  } else {
    writeln("uranium was not equal to ", isEqualTo,
             " so value stays the same...  whatever it was");
  }

  sync {
    begin { // Reader task
      writeln("Reader: waiting for uranium to be ", isEqualTo);
      uranium.waitFor(isEqualTo);
      writeln("Reader: uranium was set (by someone) to ", isEqualTo);
    }

    begin { // Writer task
      writeln("Writer: will set uranium to the value ", isEqualTo, " in...");
      countdown(3);
      uranium.write(isEqualTo);
    }
  }

// ``sync`` variables have two states: empty and full.
// If you read an empty variable or write a full variable, you are waited
// until the variable is full or empty again.
  var someSyncVar$: sync int; // varName$ is a convention not a law.
  sync {
    begin { // Reader task
      writeln("Reader: waiting to read.");
      var read_sync = someSyncVar$;
      writeln("Reader: value is ", read_sync);
    }

    begin { // Writer task
      writeln("Writer: will write in...");
      countdown(3);
      someSyncVar$ = 123;
    }
  }

// ``single`` vars can only be written once. A read on an unwritten ``single``
// results in a wait, but when the variable has a value it can be read indefinitely.
  var someSingleVar$: single int; // varName$ is a convention not a law.
  sync {
    begin { // Reader task
      writeln("Reader: waiting to read.");
      for i in 1..5 {
        var read_single = someSingleVar$;
        writeln("Reader: iteration ", i,", and the value is ", read_single);
      }
    }

    begin { // Writer task
      writeln("Writer: will write in...");
      countdown(3);
      someSingleVar$ = 5; // first and only write ever.
    }
  }

// Here's an example using atomics and a ``sync`` variable to create a
// count-down mutex (also known as a multiplexer).
  var count: atomic int; // our counter
  var lock$: sync bool;   // the mutex lock

  count.write(2);       // Only let two tasks in at a time.
  lock$.writeXF(true);  // Set lock$ to full (unlocked)
  // Note: The value doesn't actually matter, just the state
  // (full:unlocked / empty:locked)
  // Also, writeXF() fills (F) the sync var regardless of its state (X)

  coforall task in 1..5 { // Generate tasks
    // Create a barrier
    do {
      lock$;                 // Read lock$ (wait)
    } while (count.read() &lt; 1); // Keep waiting until a spot opens up

    count.sub(1);          // decrement the counter
    lock$.writeXF(true); // Set lock$ to full (signal)

    // Actual 'work'
    writeln("Task #", task, " doing work.");
    sleep(2);

    count.add(1);        // Increment the counter
    lock$.writeXF(true); // Set lock$ to full (signal)
  }

// We can define the operations ``+ * &amp; | ^ &amp;&amp; || min max minloc maxloc``
// over an entire array using scans and reductions.
// Reductions apply the operation over the entire array and
// result in a scalar value.
  var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2];
  var sumOfValues = + reduce listOfValues;
  var maxValue = max reduce listOfValues; // 'max' give just max value

// ``maxloc`` gives max value and index of the max value.
// Note: We have to zip the array and domain together with the zip iterator.
  var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues,
                                                  listOfValues.domain);

  writeln((sumOfValues, maxValue, idxOfMax, listOfValues[idxOfMax]));

// Scans apply the operation incrementally and return an array with the
// values of the operation at that index as it progressed through the
// array from ``array.domain.low`` to ``array.domain.high``.
  var runningSumOfValues = + scan listOfValues;
  var maxScan = max scan listOfValues;
  writeln(runningSumOfValues);
  writeln(maxScan);
} // end main()
</code></pre>
<p>CHICKEN:</p>
<pre><code class="lang-plaintext">;; #!/usr/bin/env csi -s

;; Run the CHICKEN REPL in the commandline as follows :
;; $ csi

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 0. Syntax
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Single line comments start with a semicolon

#| Block comments
   can span multiple lines and...
   #| can be nested
   |#
|#

;; S-expression comments are used to comment out expressions
#; (display "nothing")    ; discard this expression 

;; CHICKEN has two fundamental pieces of syntax: Atoms and S-expressions
;; an atom is something that evaluates to itself
;; all builtin data types viz. numbers, chars, booleans, strings etc. are atoms
;; Furthermore an atom can be a symbol, an identifier, a keyword, a procedure
;; or the empty list (also called null)
'athing              ;; =&gt; athing 
'+                   ;; =&gt; + 
+                    ;; =&gt; &lt;procedure C_plus&gt;

;; S-expressions (short for symbolic expressions) consists of one or more atoms
(quote +)            ;; =&gt; + ; another way of writing '+
(+ 1 2 3)            ;; =&gt; 6 ; this S-expression evaluates to a function call
'(+ 1 2 3)           ;; =&gt; (+ 1 2 3) ; evaluates to a list 


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 1. Primitive Datatypes and Operators 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Numbers
99999999999999999999 ;; integers
#b1010               ;; binary ; =&gt; 10
#o10                 ;; octal  ; =&gt; 8
#x8ded               ;; hexadecimal ; =&gt; 36333
3.14                 ;; real
6.02e+23
3/4                  ;; rational

;;Characters and Strings
#\A                  ;; A char
"Hello, World!"      ;; strings are fixed-length arrays of characters

;; Booleans
#t                  ;; true
#f                  ;; false

;; Function call is written as (f x y z ...)
;; where f is a function and x,y,z, ... are arguments
(print "Hello, World!")    ;; =&gt; Hello, World!
;; formatted output
(printf "Hello, ~a.\n" "World")  ;; =&gt; Hello, World.

;; print commandline arguments
(map print (command-line-arguments)) 

(list 'foo 'bar 'baz)          ;; =&gt; (foo bar baz)
(string-append "pine" "apple") ;; =&gt; "pineapple"
(string-ref "tapioca" 3)       ;; =&gt; #\i;; character 'i' is at index 3
(string-&gt;list "CHICKEN")       ;; =&gt; (#\C #\H #\I #\C #\K #\E #\N)
(string-intersperse '("1" "2") ":") ;; =&gt; "1:2"
(string-split "1:2:3" ":")     ;; =&gt; ("1" "2" "3")


;; Predicates are special functions that return boolean values
(atom? #t)                ;; =&gt; #t

(symbol? #t)              ;; =&gt; #f

(symbol? '+)              ;; =&gt; #t

(procedure? +)            ;; =&gt; #t

(pair? '(1 2))            ;; =&gt; #t

(pair? '(1 2 . 3))        ;; =&gt; #t

(pair? '())               ;; =&gt; #f

(list? '())               ;; =&gt; #t


;; Some arithmetic operations

(+ 1 1)                   ;; =&gt; 2
(- 8 1)                   ;; =&gt; 7
(* 10 2)                  ;; =&gt; 20
(expt 2 3)                ;; =&gt; 8
(remainder 5 2)           ;; =&gt; 1
(/ 35 5)                  ;; =&gt; 7
(/ 1 3)                   ;; =&gt; 0.333333333333333

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 2. Variables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; You can create variables with define
;; A variable name can use any character except: ()[]{}",'`;#\
(define myvar 5)
myvar        ;; =&gt; 5

;; Alias to a procedure
(define ** expt)
(** 2 3)     ;; =&gt; 8

;; Accessing an undefined variable raises an exception
s            ;; =&gt; Error: unbound variable: s

;; Local binding
(let ((me "Bob"))
  (print me))     ;; =&gt; Bob

(print me)        ;; =&gt; Error: unbound variable: me

;; Assign a new value to previously defined variable
(set! myvar 10) 
myvar             ;; =&gt; 10


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 3. Collections
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Pairs
;; 'cons' constructs pairs, 
;; 'car' extracts the first element, 'cdr' extracts the rest of the elements
(cons 'subject 'verb)       ;; =&gt; '(subject . verb)
(car (cons 'subject 'verb)) ;; =&gt; subject
(cdr (cons 'subject 'verb)) ;; =&gt; verb

;; Lists
;; cons creates a new list if the second item is a list
(cons 0 '())         ;; =&gt; (0)
(cons 1 (cons 2  (cons 3 '())))    ;; =&gt; (1 2 3)
;; 'list' is a convenience variadic constructor for lists
(list 1 2 3)    ;; =&gt; (1 2 3)


;; Use 'append' to append lists together
(append '(1 2) '(3 4)) ;; =&gt; (1 2 3 4)

;; Some basic operations on lists
(map add1 '(1 2 3))    ;; =&gt; (2 3 4)
(reverse '(1 3 4 7))   ;; =&gt; (7 4 3 1)
(sort '(11 22 33 44) &gt;)   ;; =&gt; (44 33 22 11)

(define days '(SUN MON FRI))
(list-ref days 1)      ;; =&gt; MON
(set! (list-ref days 1) 'TUE)
days                   ;; =&gt; (SUN TUE FRI)

;; Vectors
;; Vectors are heterogeneous structures whose elements are indexed by integers
;; A Vector typically occupies less space than a list of the same length
;; Random access of an element in a vector is faster than in a list
#(1 2 3)                     ;; =&gt; #(1 2 3) ;; literal syntax
(vector 'a 'b 'c)            ;; =&gt; #(a b c) 
(vector? #(1 2 3))           ;; =&gt; #t
(vector-length #(1 (2) "a")) ;; =&gt; 3
(vector-ref #(1 (2) (3 3)) 2);; =&gt; (3 3)

(define vec #(1 2 3))
(vector-set! vec 2 4)
vec                         ;; =&gt; #(1 2 4)

;; Vectors can be created from lists and vice-verca
(vector-&gt;list #(1 2 4))     ;; =&gt; '(1 2 4)
(list-&gt;vector '(a b c))     ;; =&gt; #(a b c)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 4. Functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Use 'lambda' to create functions.
;; A function always returns the value of its last expression
(lambda () "Hello World")   ;; =&gt; #&lt;procedure (?)&gt; 

;; Use extra parens around function definition to execute 
((lambda () "Hello World")) ;; =&gt; Hello World ;; argument list is empty

;; A function with an argument
((lambda (x) (* x x)) 3)           ;; =&gt; 9
;; A function with two arguments
((lambda (x y) (* x y)) 2 3)       ;; =&gt; 6

;; assign a function to a variable
(define sqr (lambda (x) (* x x)))
sqr                        ;; =&gt; #&lt;procedure (sqr x)&gt;
(sqr 3)                    ;; =&gt; 9

;; We can shorten this using the function definition syntactic sugar
(define (sqr x) (* x x))
(sqr 3)                    ;; =&gt; 9

;; We can redefine existing procedures
(foldl cons '() '(1 2 3 4 5)) ;; =&gt; (((((() . 1) . 2) . 3) . 4) . 5)
(define (foldl func accu alist)
  (if (null? alist)
    accu
    (foldl func (func (car alist) accu) (cdr alist))))

(foldl cons '() '(1 2 3 4 5))   ;; =&gt; (5 4 3 2 1)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 5. Equality
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; For numbers use '='
(= 3 3.0)                  ;; =&gt; #t
(= 2 1)                    ;; =&gt; #f

;; 'eq?' returns #t if two arguments refer to the same object in memory
;; In other words, it's a simple pointer comparison.
(eq? '() '())              ;; =&gt; #t ;; there's only one empty list in memory
(eq? (list 3) (list 3))    ;; =&gt; #f ;; not the same object
(eq? 'yes 'yes)            ;; =&gt; #t
(eq? 3 3)                  ;; =&gt; #t ;; don't do this even if it works in this case
(eq? 3 3.0)                ;; =&gt; #f ;; it's better to use '=' for number comparisons
(eq? "Hello" "Hello")      ;; =&gt; #f

;; 'eqv?' is same as 'eq?' all datatypes except numbers and characters
(eqv? 3 3.0)               ;; =&gt; #f
(eqv? (expt 2 3) (expt 2 3)) ;; =&gt; #t
(eqv? 'yes 'yes)           ;; =&gt; #t

;; 'equal?' recursively compares the contents of pairs, vectors, and strings,
;; applying eqv? on other objects such as numbers and symbols. 
;; A rule of thumb is that objects are generally equal? if they print the same.

(equal? '(1 2 3) '(1 2 3)) ;; =&gt; #t
(equal? #(a b c) #(a b c)) ;; =&gt; #t
(equal? 'a 'a)             ;; =&gt; #t
(equal? "abc" "abc")       ;; =&gt; #t

;; In Summary:
;; eq? tests if objects are identical
;; eqv? tests if objects are operationally equivalent
;; equal? tests if objects have same structure and contents

;; Comparing strings for equality
(string=? "Hello" "Hello") ;; =&gt; #t


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 6. Control Flow
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Conditionals
(if #t                     ;; test expression
  "True"                   ;; then expression
  "False")                 ;; else expression
                           ;; =&gt; "True"

(if (&gt; 3 2)
  "yes"
  "no")                    ;; =&gt; "yes"

;; In conditionals, all values that are not '#f' are treated as true.
;; 0, '(), #() "" , are all true values
(if 0
  "0 is not false"
  "0 is false")            ;; =&gt; "0 is not false"

;; 'cond' chains a series of tests and returns as soon as it encounters a true condition
;; 'cond' can be used to simulate 'if/elseif/else' statements
(cond ((&gt; 2 2) "not true so don't return this")
      ((&lt; 2 5) "true, so return this")
      (else "returning default"))    ;; =&gt; "true, so return this"


;; A case expression is evaluated as follows:
;; The key is evaluated and compared with each datum in sense of 'eqv?',
;; The corresponding clause in the matching datum is evaluated and returned as result
(case (* 2 3)              ;; the key is 6
  ((2 3 5 7) 'prime)       ;; datum 1
  ((1 4 6 8) 'composite))  ;; datum 2; matched!
                           ;; =&gt; composite

;; case with else clause
(case (car '(c d))
  ((a e i o u) 'vowel)
  ((w y) 'semivowel)
  (else 'consonant))       ;; =&gt;  consonant

;; Boolean expressions
;; 'and' returns the first expression that evaluates to #f
;; otherwise, it returns the result of the last expression
(and #t #f (= 2 2.0))                ;; =&gt; #f
(and (&lt; 2 5) (&gt; 2 0) "0 &lt; 2 &lt; 5")    ;; =&gt; "0 &lt; 2 &lt; 5"

;; 'or' returns the first expression that evaluates to #t 
;; otherwise the result of the last expression is returned
(or #f #t #f)                        ;; =&gt; #t
(or #f #f #f)                        ;; =&gt; #f

;; 'when' is like 'if' without the else expression
(when (positive? 5) "I'm positive")  ;; =&gt; "I'm positive"

;; 'unless' is equivalent to (when (not &lt;test&gt;) &lt;expr&gt;)
(unless (null? '(1 2 3)) "not null") ;; =&gt; "not null"


;; Loops
;; loops can be created with the help of tail-recursions
(define (loop count)
  (unless (= count 0)
    (print "hello") 
    (loop (sub1 count))))
(loop 4)                             ;; =&gt; hello, hello ...

;; Or with a named let
(let loop ((i 0) (limit 5))
  (when (&lt; i limit)
    (printf "i = ~a\n" i)
    (loop (add1 i) limit)))          ;; =&gt; i = 0, i = 1....

;; 'do' is another iteration construct
;; It initializes a set of variables and updates them in each iteration
;; A final expression is evaluated after the exit condition is met
(do ((x 0 (add1 x )))            ;; initialize x = 0 and add 1 in each iteration
  ((= x 10) (print "done"))      ;; exit condition and final expression
  (print x))                     ;; command to execute in each step
                                 ;; =&gt; 0,1,2,3....9,done

;; Iteration over lists 
(for-each (lambda (a) (print (* a a)))
          '(3 5 7))                  ;; =&gt; 9, 25, 49

;; 'map' is like for-each but returns a list
(map add1 '(11 22 33))               ;; =&gt; (12 23 34)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 7. Extensions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; The CHICKEN core is very minimal, but additional features are provided by library extensions known as Eggs.
;; You can install Eggs with 'chicken-install &lt;eggname&gt;' command.

;; complex numbers
3+4i                               ;; =&gt; 3+2i
;; Supports fractions without falling back to inexact flonums
1/3                                ;; =&gt; 1/3
;; provides support for large integers through bignums
(expt 9 20)                        ;; =&gt; 12157665459056928801 
;; And other 'extended' functions
(log 10 (exp 1))                   ;; =&gt; 2.30258509299405
(numerator 2/3)                    ;; =&gt; 2

;; 'utf8' provides unicode support
(import utf8)
"\u03BBx:(\u03BC\u0251.\u0251\u2192\u0251).xx" ;; =&gt; "λx:(μɑ.ɑ→ɑ).xx"

;; 'posix' provides file I/O and lots of other services for unix-like operating systems
;; Some of the functions are not available in Windows system,
;; See http://wiki.call-cc.org/man/5/Module%20(chicken%20file%20posix) for more details

;; Open a file to append, open "write only" and create file if it does not exist
(define outfn (file-open "chicken-hen.txt" (+ open/append open/wronly open/creat)))
;; write some text to the file
(file-write outfn "Did chicken came before hen?") 
;; close the file
(file-close outfn)
;; Open the file "read only"
(define infn (file-open "chicken-hen.txt" open/rdonly))
;; read some text from the file
(file-read infn 30)         ;; =&gt; ("Did chicken came before hen?  ", 28)
(file-close infn)

;; CHICKEN also supports SRFI (Scheme Requests For Implementation) extensions
;; See 'http://srfi.schemers.org/srfi-implementers.html" to see srfi's supported by CHICKEN
(import srfi-1)                    ;; list library
(filter odd? '(1 2 3 4 5 6 7))     ;; =&gt; (1 3 5 7)
(count even? '(1 2 3 4 5))         ;; =&gt; 2
(take '(12 24 36 48 60) 3)         ;; =&gt; (12 24 36)
(drop '(12 24 36 48 60) 2)         ;; =&gt; (36 48 60)
(circular-list 'z 'q)              ;; =&gt; z q z q ...

(import srfi-13)                   ;; string library
(string-reverse "pan")             ;; =&gt; "nap"
(string-index "Turkey" #\k)        ;; =&gt; 3
(string-every char-upper-case? "CHICKEN") ;; =&gt; #t
(string-join '("foo" "bar" "baz") ":")    ;; =&gt; "foo:bar:baz"


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 8. Macros
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; A 'for .. in ..' iteration like python, for lists
(define-syntax for
  (syntax-rules (in)
                ((for elem in alist body ...)
                 (for-each (lambda (elem) body ...) alist))))

(for x in '(2 4 8 16)
     (print x))          ;; =&gt; 2, 4, 8, 16

(for chr in (string-&gt;list "PENCHANT")
     (print chr))        ;; =&gt; P, E, N, C, H, A, N, T

;; While loop
(define-syntax while
  (syntax-rules ()
                ((while cond body ...)
                 (let loop ()
                   (when cond
                     body ...
                     (loop))))))

(let ((str "PENCHANT") (i 0))
  (while (&lt; i (string-length str))     ;; while (condition)
         (print (string-ref str i))    ;; body 
         (set! i (add1 i))))           
                                       ;; =&gt; P, E, N, C, H, A, N, T

;; Advanced Syntax-Rules Primer -&gt; http://petrofsky.org/src/primer.txt
;; Macro system in chicken -&gt; http://lists.gnu.org/archive/html/chicken-users/2008-04/msg00013.html

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 9. Modules
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Also See http://wiki.call-cc.org/man/5/Modules

;; The 'test' module exports a value named 'hello' and a macro named 'greet'
(module test (hello greet)
  (import scheme)

  (define-syntax greet
    (syntax-rules ()
      ((_ whom) 
       (begin
         (display "Hello, ")
         (display whom)
         (display " !\n") ) ) ) )

  (define (hello)
    (greet "world") )  )

;; we can define our modules in a separate file (say test.scm) and load them to the interpreter with
;;         (load "test.scm")

;; import the module
(import test)
(hello)                ;; =&gt; Hello, world !
(greet "schemers")     ;; =&gt; Hello, schemers !

;; We can compile the module files in to shared libraries by using following command,
;;         csc -s test.scm
;;         (load "test.so")

;; Functors
;; Functors are high level modules that can be parameterized by other modules
;; Following functor requires another module named 'M' that provides a function called 'multiply'
;; The functor itself exports a generic function 'square'
(functor (squaring-functor (M (multiply))) (square)
         (import scheme M) 
         (define (square x) (multiply x x)))

;; Module 'nums' can be passed as a parameter to 'squaring-functor'
(module nums (multiply) 
        (import scheme)     ;; predefined modules
        (define (multiply x y) (* x y))) 
;; the final module can be imported and used in our program
(module number-squarer = (squaring-functor nums)) 

(import number-squarer)
(square 3)              ;; =&gt; 9

;; We can instantiate the functor for other inputs
;; Here's another example module that can be passed to squaring-functor
(module stars (multiply)
        (import chicken scheme)  ;; chicken module for the 'use' keyword
        (use srfi-1)             ;; we can use external libraries in our module
        (define (multiply x y)
          (list-tabulate x (lambda _ (list-tabulate y (lambda _ '*))))))
(module star-squarer = (squaring-functor stars))

(import star-squarer)
(square 3)              ;; =&gt; ((* * *)(* * *)(* * *))
</code></pre>
<p>citron:</p>
<pre><code class="lang-plaintext"># Comments start with a '#'
# All comments encompass a single line

###########################################
## 1. Primitive Data types and Operators
###########################################

# You have numbers
3. # 3

# Numbers are all doubles in interpreted mode

# Mathematical operator precedence is not respected.
# binary 'operators' are evaluated in ltr order
1 + 1. # 2
8 - 4. # 4
10 + 2 * 3. # 36

# Division is always floating division
35 / 2 # 17.5.

# Integer division is non-trivial, you may use floor
(35 / 2) floor # 17.

# Booleans are primitives
True.
False.

# Boolean messages
True not. # False
False not. # True
1 = 1. # True
1 !=: 1. # False
1 &lt; 10. # True

# Here, `not` is a unary message to the object `Boolean`
# Messages are comparable to instance method calls
# And they have three different forms:
#   1. Unary messages: Length &gt; 1, and they take no arguments:
        False not.
#   2. Binary Messages: Length = 1, and they take a single argument:
        False &amp; True.
#   3. Keyword messages: must have at least one ':', they take as many arguments
#      as they have `:` s
        False either: 1 or: 2. # 2

# Strings
'This is a string'.
'There are no character types exposed to the user'.
# "You cannot use double quotes for strings" &lt;- Error

# Strins can be summed
'Hello, ' + 'World!'. # 'Hello, World!'

# Strings allow access to their characters
'This is a beautiful string' at: 0. # 'T'

###########################################
## intermission: Basic Assignment
###########################################

# You may assign values to the current scope:
var name is value. # assigns `value` into `name`

# You may also assign values into the current object's namespace
my name is value. # assigns `value` into the current object's `name` property

# Please note that these names are checked at compile (read parse if in interpreted mode) time
# but you may treat them as dynamic assignments anyway

###########################################
## 2. Lists(Arrays?) and Tuples
###########################################

# Arrays are allowed to have multiple types
Array new &lt; 1 ; 2 ; 'string' ; Nil. # Array new &lt; 1 ; 2 ; 'string' ; Nil

# Tuples act like arrays, but are immutable.
# Any shenanigans degrade them to arrays, however
[1, 2, 'string']. # [1, 2, 'string']

# They can interoperate with arrays
[1, 'string'] + (Array new &lt; 'wat'). # Array new &lt; 1 ; 'string' ; 'wat'

# Indexing into them
[1, 2, 3] at: 1. # 2

# Some array operations
var arr is Array new &lt; 1 ; 2 ; 3.

arr head. # 1
arr tail. # Array new &lt; 2 ; 3.
arr init. # Array new &lt; 1 ; 2.
arr last. # 3
arr push: 4. # Array new &lt; 1 ; 2 ; 3 ; 4.
arr pop. # 4
arr pop: 1. # 2, `arr` is rebound to Array new &lt; 1 ; 3.

# List comprehensions
[x * 2 + y,, arr, arr + [4, 5],, x &gt; 1]. # Array ← 7 ; 9 ; 10 ; 11
# fresh variable names are bound as they are encountered,
# so `x` is bound to the values in `arr`
# and `y` is bound to the values in `arr + [4, 5]`
#
# The general format is: [expr,, bindings*,, predicates*]


####################################
## 3. Functions
####################################

# A simple function that takes two variables
var add is {:a:b ^a + b.}.

# this function will resolve all its names except the formal arguments
# in the context it is called in.

# Using the function
add applyTo: 3 and: 5. # 8
add applyAll: [3, 5]. # 8

# Also a (customizable -- more on this later) pseudo-operator allows for a shorthand
# of function calls
# By default it is REF[args]

add[3, 5]. # 8

# To customize this behaviour, you may simply use a compiler pragma:
#:callShorthand ()

# And then you may use the specified operator.
# Note that the allowed 'operator' can only be made of any of these: []{}()
# And you may mix-and-match (why would anyone do that?)

add(3, 5). # 8

# You may also use functions as operators in the following way:

3 `add` 5. # 8
# This call binds as such: add[(3), 5]
# because the default fixity is left, and the default precedence is 1

# You may change the precedence/fixity of this operator with a pragma
#:declare infixr 1 add

3 `add` 5. # 8
# now this binds as such: add[3, (5)].

# There is another form of functions too
# So far, the functions were resolved in a dynamic fashion
# But a lexically scoped block is also possible
var sillyAdd is {\:x:y add[x,y].}.

# In these blocks, you are not allowed to declare new variables
# Except with the use of Object::'letEqual:in:`
# And the last expression is implicitly returned.

# You may also use a shorthand for lambda expressions
var mul is \:x:y x * y.

# These capture the named bindings that are not present in their
# formal parameters, and retain them. (by ref)

###########################################
## 5. Control Flow
###########################################

# inline conditional-expressions
var citron is 1 = 1 either: 'awesome' or: 'awful'. # citron is 'awesome'

# multiple lines is fine too
var citron is 1 = 1
    either: 'awesome'
    or:     'awful'.

# looping
10 times: {:x
    Pen writeln: x.
}. # 10. -- side effect: 10 lines in stdout, with numbers 0 through 9 in them

# Citron properly supports tail-call recursion in lexically scoped blocks
# So use those to your heart's desire

# mapping most data structures is as simple as `fmap:`
[1, 2, 3, 4] fmap: \:x x + 1. # [2, 3, 4, 5]

# You can use `foldl:accumulator:` to fold a list/tuple
[1, 2, 3, 4] foldl: (\:acc:x acc * 2 + x) accumulator: 4. # 90

# That expression is the same as
(2 * (2 * (2 * (2 * 4 + 1) + 2) + 3) + 4)

###################################
## 6. IO
###################################

# IO is quite simple
# With `Pen` being used for console output
# and Program::'input' and Program::'waitForInput' being used for console input

Pen writeln: 'Hello, ocean!' # prints 'Hello, ocean!\n' to the terminal

Pen writeln: Program waitForInput. # reads a line and prints it back
</code></pre>
<p>Clojure:</p>
<pre><code class="lang-plaintext">; Comments start with semicolons.

; Clojure is written in "forms", which are just
; lists of things inside parentheses, separated by whitespace.
;
; The clojure reader assumes that the first thing is a
; function or macro to call, and the rest are arguments.

; The first call in a file should be ns, to set the namespace
(ns learnclojure)

; More basic examples:

; str will create a string out of all its arguments
(str "Hello" " " "World") ; =&gt; "Hello World"

; Math is straightforward
(+ 1 1) ; =&gt; 2
(- 2 1) ; =&gt; 1
(* 1 2) ; =&gt; 2
(/ 2 1) ; =&gt; 2

; Equality is =
(= 1 1) ; =&gt; true
(= 2 1) ; =&gt; false

; You need not for logic, too
(not true) ; =&gt; false

; Nesting forms works as you expect
(+ 1 (- 3 2)) ; = 1 + (3 - 2) =&gt; 2

; Types
;;;;;;;;;;;;;

; Clojure uses Java's object types for booleans, strings and numbers.
; Use `class` to inspect them.
(class 1) ; Integer literals are java.lang.Long by default
(class 1.); Float literals are java.lang.Double
(class ""); Strings always double-quoted, and are java.lang.String
(class false) ; Booleans are java.lang.Boolean
(class nil); The "null" value is called nil

; If you want to create a literal list of data, use ' to stop it from
; being evaluated
'(+ 1 2) ; =&gt; (+ 1 2)
; (shorthand for (quote (+ 1 2)))

; You can eval a quoted list
(eval '(+ 1 2)) ; =&gt; 3

; Collections &amp; Sequences
;;;;;;;;;;;;;;;;;;;

; Lists are linked-list data structures, while Vectors are array-backed.
; Vectors and Lists are java classes too!
(class [1 2 3]); =&gt; clojure.lang.PersistentVector
(class '(1 2 3)); =&gt; clojure.lang.PersistentList

; A list would be written as just (1 2 3), but we have to quote
; it to stop the reader thinking it's a function.
; Also, (list 1 2 3) is the same as '(1 2 3)

; "Collections" are just groups of data
; Both lists and vectors are collections:
(coll? '(1 2 3)) ; =&gt; true
(coll? [1 2 3]) ; =&gt; true

; "Sequences" (seqs) are abstract descriptions of lists of data.
; Only lists are seqs.
(seq? '(1 2 3)) ; =&gt; true
(seq? [1 2 3]) ; =&gt; false

; A seq need only provide an entry when it is accessed.
; So, seqs which can be lazy -- they can define infinite series:
(range 4) ; =&gt; (0 1 2 3)
(range) ; =&gt; (0 1 2 3 4 ...) (an infinite series)
(take 4 (range)) ;  (0 1 2 3)

; Use cons to add an item to the beginning of a list or vector
(cons 4 [1 2 3]) ; =&gt; (4 1 2 3)
(cons 4 '(1 2 3)) ; =&gt; (4 1 2 3)

; Conj will add an item to a collection in the most efficient way.
; For lists, they insert at the beginning. For vectors, they insert at the end.
(conj [1 2 3] 4) ; =&gt; [1 2 3 4]
(conj '(1 2 3) 4) ; =&gt; (4 1 2 3)

; Use concat to add lists or vectors together
(concat [1 2] '(3 4)) ; =&gt; (1 2 3 4)

; Use filter, map to interact with collections
(map inc [1 2 3]) ; =&gt; (2 3 4)
(filter even? [1 2 3]) ; =&gt; (2)

; Use reduce to reduce them
(reduce + [1 2 3 4])
; = (+ (+ (+ 1 2) 3) 4)
; =&gt; 10

; Reduce can take an initial-value argument too
(reduce conj [] '(3 2 1))
; = (conj (conj (conj [] 3) 2) 1)
; =&gt; [3 2 1]

; Functions
;;;;;;;;;;;;;;;;;;;;;

; Use fn to create new functions. A function always returns
; its last statement.
(fn [] "Hello World") ; =&gt; fn

; (You need extra parens to call it)
((fn [] "Hello World")) ; =&gt; "Hello World"

; You can create a var using def
(def x 1)
x ; =&gt; 1

; Assign a function to a var
(def hello-world (fn [] "Hello World"))
(hello-world) ; =&gt; "Hello World"

; You can shorten this process by using defn
(defn hello-world [] "Hello World")

; The [] is the list of arguments for the function.
(defn hello [name]
  (str "Hello " name))
(hello "Steve") ; =&gt; "Hello Steve"

; You can also use this shorthand to create functions:
(def hello2 #(str "Hello " %1))
(hello2 "Julie") ; =&gt; "Hello Julie"

; You can have multi-variadic functions, too
(defn hello3
  ([] "Hello World")
  ([name] (str "Hello " name)))
(hello3 "Jake") ; =&gt; "Hello Jake"
(hello3) ; =&gt; "Hello World"

; Functions can pack extra arguments up in a seq for you
(defn count-args [&amp; args]
  (str "You passed " (count args) " args: " args))
(count-args 1 2 3) ; =&gt; "You passed 3 args: (1 2 3)"

; You can mix regular and packed arguments
(defn hello-count [name &amp; args]
  (str "Hello " name ", you passed " (count args) " extra args"))
(hello-count "Finn" 1 2 3)
; =&gt; "Hello Finn, you passed 3 extra args"


; Maps
;;;;;;;;;;

; Hash maps and array maps share an interface. Hash maps have faster lookups
; but don't retain key order.
(class {:a 1 :b 2 :c 3}) ; =&gt; clojure.lang.PersistentArrayMap
(class (hash-map :a 1 :b 2 :c 3)) ; =&gt; clojure.lang.PersistentHashMap

; Arraymaps will automatically become hashmaps through most operations
; if they get big enough, so you don't need to worry.

; Maps can use any hashable type as a key, but usually keywords are best
; Keywords are like strings with some efficiency bonuses
(class :a) ; =&gt; clojure.lang.Keyword

(def stringmap {"a" 1, "b" 2, "c" 3})
stringmap  ; =&gt; {"a" 1, "b" 2, "c" 3}

(def keymap {:a 1, :b 2, :c 3})
keymap ; =&gt; {:a 1, :c 3, :b 2}

; By the way, commas are always treated as whitespace and do nothing.

; Retrieve a value from a map by calling it as a function
(stringmap "a") ; =&gt; 1
(keymap :a) ; =&gt; 1

; Keywords can be used to retrieve their value from a map, too!
(:b keymap) ; =&gt; 2

; Don't try this with strings.
;("a" stringmap)
; =&gt; Exception: java.lang.String cannot be cast to clojure.lang.IFn

; Retrieving a non-present key returns nil
(stringmap "d") ; =&gt; nil

; Use assoc to add new keys to hash-maps
(def newkeymap (assoc keymap :d 4))
newkeymap ; =&gt; {:a 1, :b 2, :c 3, :d 4}

; But remember, clojure types are immutable!
keymap ; =&gt; {:a 1, :b 2, :c 3}

; Use dissoc to remove keys
(dissoc keymap :a :b) ; =&gt; {:c 3}

; Sets
;;;;;;

(class #{1 2 3}) ; =&gt; clojure.lang.PersistentHashSet
(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; =&gt; #{1 2 3}

; Add a member with conj
(conj #{1 2 3} 4) ; =&gt; #{1 2 3 4}

; Remove one with disj
(disj #{1 2 3} 1) ; =&gt; #{2 3}

; Test for existence by using the set as a function:
(#{1 2 3} 1) ; =&gt; 1
(#{1 2 3} 4) ; =&gt; nil

; There are more functions in the clojure.sets namespace.

; Useful forms
;;;;;;;;;;;;;;;;;

; Logic constructs in clojure are just macros, and look like
; everything else
(if false "a" "b") ; =&gt; "b"
(if false "a") ; =&gt; nil

; Use let to create temporary bindings
(let [a 1 b 2]
  (&gt; a b)) ; =&gt; false

; Group statements together with do
(do
  (print "Hello")
  "World") ; =&gt; "World" (prints "Hello")

; Functions have an implicit do
(defn print-and-say-hello [name]
  (print "Saying hello to " name)
  (str "Hello " name))
(print-and-say-hello "Jeff") ;=&gt; "Hello Jeff" (prints "Saying hello to Jeff")

; So does let
(let [name "Urkel"]
  (print "Saying hello to " name)
  (str "Hello " name)) ; =&gt; "Hello Urkel" (prints "Saying hello to Urkel")


; Use the threading macros (-&gt; and -&gt;&gt;) to express transformations of
; data more clearly.

; The "Thread-first" macro (-&gt;) inserts into each form the result of
; the previous, as the first argument (second item)
(-&gt;  
   {:a 1 :b 2} 
   (assoc :c 3) ;=&gt; (assoc {:a 1 :b 2} :c 3)
   (dissoc :b)) ;=&gt; (dissoc (assoc {:a 1 :b 2} :c 3) :b)

; This expression could be written as:
; (dissoc (assoc {:a 1 :b 2} :c 3) :b)
; and evaluates to {:a 1 :c 3}

; The double arrow does the same thing, but inserts the result of
; each line at the *end* of the form. This is useful for collection
; operations in particular:
(-&gt;&gt;
   (range 10)
   (map inc)     ;=&gt; (map inc (range 10))
   (filter odd?) ;=&gt; (filter odd? (map inc (range 10)))
   (into []))    ;=&gt; (into [] (filter odd? (map inc (range 10))))
                 ; Result: [1 3 5 7 9]

; When you are in a situation where you want more freedom as where to
; put the result of previous data transformations in an 
; expression, you can use the as-&gt; macro. With it, you can assign a
; specific name to transformations' output and use it as a
; placeholder in your chained expressions:

(as-&gt; [1 2 3] input
  (map inc input);=&gt; You can use last transform's output at the last position
  (nth input 2) ;=&gt;  and at the second position, in the same expression
  (conj [4 5 6] input 8 9 10)) ;=&gt; or in the middle !
                               ; Result: [4 5 6 4 8 9 10]


; Modules
;;;;;;;;;;;;;;;

; Use "use" to get all functions from the module
(use 'clojure.set)

; Now we can use set operations
(intersection #{1 2 3} #{2 3 4}) ; =&gt; #{2 3}
(difference #{1 2 3} #{2 3 4}) ; =&gt; #{1}

; You can choose a subset of functions to import, too
(use '[clojure.set :only [intersection]])

; Use require to import a module
(require 'clojure.string)

; Use / to call functions from a module
; Here, the module is clojure.string and the function is blank?
(clojure.string/blank? "") ; =&gt; true

; You can give a module a shorter name on import
(require '[clojure.string :as str])
(str/replace "This is a test." #"[a-o]" str/upper-case) ; =&gt; "THIs Is A tEst."
; (#"" denotes a regular expression literal)

; You can use require (and use, but don't) from a namespace using :require.
; You don't need to quote your modules if you do it this way.
(ns test
  (:require
    [clojure.string :as str]
    [clojure.set :as set]))

; Java
;;;;;;;;;;;;;;;;;

; Java has a huge and useful standard library, so
; you'll want to learn how to get at it.

; Use import to load a java module
(import java.util.Date)

; You can import from an ns too.
(ns test
  (:import java.util.Date
           java.util.Calendar))

; Use the class name with a "." at the end to make a new instance
(Date.) ; &lt;a date object&gt;

; Use . to call methods. Or, use the ".method" shortcut
(. (Date.) getTime) ; &lt;a timestamp&gt;
(.getTime (Date.)) ; exactly the same thing.

; Use / to call static methods
(System/currentTimeMillis) ; &lt;a timestamp&gt; (system is always present)

; Use doto to make dealing with (mutable) classes more tolerable
(import java.util.Calendar)
(doto (Calendar/getInstance)
  (.set 2000 1 1 0 0 0)
  .getTime) ; =&gt; A Date. set to 2000-01-01 00:00:00

; STM
;;;;;;;;;;;;;;;;;

; Software Transactional Memory is the mechanism clojure uses to handle
; persistent state. There are a few constructs in clojure that use this.

; An atom is the simplest. Pass it an initial value
(def my-atom (atom {}))

; Update an atom with swap!.
; swap! takes a function and calls it with the current value of the atom
; as the first argument, and any trailing arguments as the second
(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1)
(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2)

; Use '@' to dereference the atom and get the value
my-atom  ;=&gt; Atom&lt;#...&gt; (Returns the Atom object)
@my-atom ; =&gt; {:a 1 :b 2}

; Here's a simple counter using an atom
(def counter (atom 0))
(defn inc-counter []
  (swap! counter inc))

(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)

@counter ; =&gt; 5

; Other STM constructs are refs and agents.
; Refs: http://clojure.org/refs
; Agents: http://clojure.org/agents
</code></pre>
<p>Clojure:</p>
<pre><code class="lang-plaintext">;; Define a macro using defmacro. Your macro should output a list that can
;; be evaluated as clojure code.
;;
;; This macro is the same as if you wrote (reverse "Hello World")
(defmacro my-first-macro []
  (list reverse "Hello World"))

;; Inspect the result of a macro using macroexpand or macroexpand-1.
;;
;; Note that the call must be quoted.
(macroexpand '(my-first-macro))
;; -&gt; (#&lt;core$reverse clojure.core$reverse@xxxxxxxx&gt; "Hello World")

;; You can eval the result of macroexpand directly:
(eval (macroexpand '(my-first-macro)))
; -&gt; (\d \l \o \r \W \space \o \l \l \e \H)

;; But you should use this more succinct, function-like syntax:
(my-first-macro)  ; -&gt; (\d \l \o \r \W \space \o \l \l \e \H)

;; You can make things easier on yourself by using the more succinct quote syntax
;; to create lists in your macros:
(defmacro my-first-quoted-macro []
  '(reverse "Hello World"))

(macroexpand '(my-first-quoted-macro))
;; -&gt; (reverse "Hello World")
;; Notice that reverse is no longer function object, but a symbol.

;; Macros can take arguments.
(defmacro inc2 [arg]
  (list + 2 arg))

(inc2 2) ; -&gt; 4

;; But, if you try to do this with a quoted list, you'll get an error, because
;; the argument will be quoted too. To get around this, clojure provides a
;; way of quoting macros: `. Inside `, you can use ~ to get at the outer scope
(defmacro inc2-quoted [arg]
  `(+ 2 ~arg))

(inc2-quoted 2)

;; You can use the usual destructuring args. Expand list variables using ~@
(defmacro unless [arg &amp; body]
  `(if (not ~arg)
     (do ~@body))) ; Remember the do!

(macroexpand '(unless true (reverse "Hello World")))
;; -&gt;
;; (if (clojure.core/not true) (do (reverse "Hello World")))

;; (unless) evaluates and returns its body if the first argument is false.
;; Otherwise, it returns nil

(unless true "Hello") ; -&gt; nil
(unless false "Hello") ; -&gt; "Hello"

;; Used without care, macros can do great evil by clobbering your vars
(defmacro define-x []
  '(do
     (def x 2)
     (list x)))

(def x 4)
(define-x) ; -&gt; (2)
(list x) ; -&gt; (2)

;; To avoid this, use gensym to get a unique identifier
(gensym 'x) ; -&gt; x1281 (or some such thing)

(defmacro define-x-safely []
  (let [sym (gensym 'x)]
    `(do
       (def ~sym 2)
       (list ~sym))))

(def x 4)
(define-x-safely) ; -&gt; (2)
(list x) ; -&gt; (4)

;; You can use # within ` to produce a gensym for each symbol automatically
(defmacro define-x-hygienically []
  `(do
     (def x# 2)
     (list x#)))

(def x 4)
(define-x-hygienically) ; -&gt; (2)
(list x) ; -&gt; (4)

;; It's typical to use helper functions with macros. Let's create a few to
;; help us support a (dumb) inline arithmetic syntax
(declare inline-2-helper)
(defn clean-arg [arg]
  (if (seq? arg)
    (inline-2-helper arg)
    arg))

(defn apply-arg
  "Given args [x (+ y)], return (+ x y)"
  [val [op arg]]
  (list op val (clean-arg arg)))

(defn inline-2-helper
  [[arg1 &amp; ops-and-args]]
  (let [ops (partition 2 ops-and-args)]
    (reduce apply-arg (clean-arg arg1) ops)))

;; We can test it immediately, without creating a macro
(inline-2-helper '(a + (b - 2) - (c * 5))) ; -&gt; (- (+ a (- b 2)) (* c 5))

; However, we'll need to make it a macro if we want it to be run at compile time
(defmacro inline-2 [form]
  (inline-2-helper form))

(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
; -&gt; (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)

(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
; -&gt; 3 (actually, 3N, since the number got cast to a rational fraction with /)
</code></pre>
<p>COBOL:</p>
<pre><code class="lang-plaintext">      *COBOL. Coding like it's 1985.
      *Compiles with GnuCOBOL in OpenCobolIDE 4.7.6.

      *COBOL has significant differences between legacy (COBOL-85)
      *and modern (COBOL-2002 and COBOL-2014) versions.
      *Legacy versions require columns 1-6 to be blank (they are used
      *to store the index number of the punched card).
      *A '*' in column 7 means a comment.
      *In legacy COBOL, a comment can only be a full line.
      *Modern COBOL doesn't require fixed columns and uses *&gt; for
      *a comment, which can appear in the middle of a line.
      *Legacy COBOL also imposes a limit on maximum line length.
      *Keywords have to be in capitals in legacy COBOL,
      *but are case insensitive in modern.
      *Although modern COBOL allows you to use mixed-case characters
      *it is still common to use all caps when writing COBOL code.
      *This is what most professional COBOL developers do.
      *COBOL statements end with a period.

      *COBOL code is broken up into 4 divisions.
      *Those divisions, in order, are:
      *IDENTIFICATION DIVISION.
      *ENVIRONMENT DIVISION.
      *DATA DIVISION.
      *PROCEDURE DIVISION.

      *First, we must give our program an ID.
      *The IDENTIFICATION DIVISION can include other values too,
      *but they are comments only. PROGRAM-ID is the only one that
      *is mandatory.
       IDENTIFICATION DIVISION.
           PROGRAM-ID.    LEARN.
           AUTHOR.        JOHN DOE.
           DATE-WRITTEN.  05/02/2020.

      *Let's declare some variables.
      *We do this in the WORKING-STORAGE section within the DATA DIVISION.
      *Each data item (aka variable) starts with a level number,
      *then the name of the item, followed by a PICTURE clause
      *describing the type of data that the variable will contain.
      *Almost every COBOL programmer will abbreviate PICTURE as PIC.
      *A is for alphabetic, X is for alphanumeric, and 9 is for numeric.

      *example:
       01  MYNAME PIC XXXXXXXXXX.    *&gt; A 10 character string.

      *But counting all those Xs can lead to errors,
      *so the above code can be re-written as
       01  MYNAME PIC X(10).

      *Here are some more examples:
       01  AGE             PICTURE  9(3).   *&gt; A number up to 3 digits.
       01  BIRTH_YEAR      PIC      S9(7).  *&gt; A signed number up to 7 digits.
       01  LAST_NAME       PIC      X(10).  *&gt; A string up to 10 characters.

      *In COBOL, multiple spaces are the same as a single space, so it
      *is common to use multiple spaces to line up your code so that it
      *is easier for other coders to read.


      *Now let's write some code. Here is a simple, Hello World program.
       IDENTIFICATION DIVISION.
       PROGRAM-ID. HELLO.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 THE-MESSAGE      PIC X(20).
       PROCEDURE DIVISION.
           DISPLAY "STARTING PROGRAM".
           MOVE "HELLO WORLD" TO THE-MESSAGE.
           DISPLAY THE-MESSAGE.
           STOP RUN.

      *The above code will output:
      *STARTING PROGRAM
      *HELLO WORLD



      ********COBOL can perform math***************
       ADD 1 TO AGE GIVING NEW-AGE.
       SUBTRACT 1 FROM COUNT.
       DIVIDE VAR-1 INTO VAR-2 GIVING VAR-3.
       COMPUTE TOTAL-COUNT = COUNT1 PLUS COUNT2.


      *********PERFORM********************
      *The PERFORM keyword allows you to jump to another specified
      *section of the code, and then to return to the next executable
      *statement once the specified section of code is completed.
      *You must write the full word, PERFORM, you cannot abbreviate it.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. HELLOCOBOL.

       PROCEDURE DIVISION.
           FIRST-PARA.
               DISPLAY 'THIS IS IN FIRST-PARA'.
      *skip SECOND-PARA and perform 3rd &amp; 4th
      *then after performing THIRD-PARA and FOURTH-PARA,
      *return here and continue the program until STOP RUN.
           PERFORM THIRD-PARA THRU FOURTH-PARA.

           SECOND-PARA.
               DISPLAY 'THIS IS IN SECOND-PARA'.

           STOP RUN.

           THIRD-PARA.
               DISPLAY 'THIS IS IN THIRD-PARA'.

           FOURTH-PARA.
               DISPLAY 'THIS IS IN FOURTH-PARA'.


      *When you compile and execute the above program, it produces the
      *following result (note the order):
      *THIS IS IN FIRST-PARA
      *THIS IS IN THIRD-PARA
      *THIS IS IN FOURTH-PARA
      *THIS IS IN SECOND-PARA


      **********Combining variables together using STRING ***********

      *Now it is time to learn about two related COBOL verbs: STRING and
      *UNSTRING.

      *The STRING verb is used to concatenate, or put together, two or
      *more strings.
      *UNSTRING is used, not surprisingly, to separate a
      *string into two or more smaller strings.
      *It is important that you remember to use DELIMITED BY when you
      *are using STRING or UNSTRING in your program.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. LEARNING.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 FULL-NAME PIC X(20).
       01 FIRST-NAME PIC X(13) VALUE "BOB GIBBERISH".
       01 LAST-NAME PIC X(5) VALUE "COBB".
       PROCEDURE DIVISION.
           STRING FIRST-NAME DELIMITED BY SPACE
             " "
             LAST-NAME DELIMITED BY SIZE
             INTO FULL-NAME
           END-STRING.
           DISPLAY "THE FULL NAME IS: "FULL-NAME.
       STOP RUN.


      *The above code will output:
      *THE FULL NAME IS: BOB COBB


      *Let's examine it to see why.

      *First, we declared all of our variables, including the one that
      *we are creating by the string command, in the DATA DIVISION.

      *The action takes place down in the PROCEDURE DIVISION.
      *We start with the STRING keyword and end with END-STRING. In
      *between we list what we want to combine together into the larger,
      *master variable. Here, we are combining FIRST-NAME, a space, and
      *LAST-NAME.

      *The DELIMITED BY phrase that follows FIRST-NAME and
      *LAST-NAME tells the program how much of each variable we want to
      *capture.
      *DELIMITED BY SPACE tells the program to start at the beginning,
      *and capture the variable until it runs into a space.
      *DELIMITED BY SIZE tells the program to capture the full size of
      *the variable.
      *Since we have DELIMITED BY SPACE after FIRST-NAME, the GIBBERISH
      *part is ignored.

      *To make this clearer, change line 10 in the above code to
           STRING FIRST-NAME DELIMITED BY SIZE
      *and then re-run the program. This time the output is:
      *THE FULL NAME IS: BOB GIBBERISH COBB
</code></pre>
<p>CoffeeScript:</p>
<pre><code class="lang-plaintext"># Comments are similar to Ruby and Python, using the hash symbol `#`

###
Block comments are like these, and they translate directly to '/ *'s and '* /'s
for the resulting JavaScript code.

You should understand most of JavaScript semantics
before continuing.
###

# Assignment:
number   = 42 #=&gt; var number = 42;
opposite = true #=&gt; var opposite = true;

# Conditions:
number = -42 if opposite #=&gt; if(opposite) { number = -42; }

# Functions:
square = (x) -&gt; x * x #=&gt; var square = function(x) { return x * x; }

fill = (container, liquid = "coffee") -&gt;
  "Filling the #{container} with #{liquid}..."
#=&gt;var fill;
#
#fill = function(container, liquid) {
#  if (liquid == null) {
#    liquid = "coffee";
#  }
#  return "Filling the " + container + " with " + liquid + "...";
#};

# Ranges:
list = [1..5] #=&gt; var list = [1, 2, 3, 4, 5];

# Objects:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -&gt; x * square x
#=&gt; var math = {
#    "root": Math.sqrt,
#    "square": square,
#    "cube": function(x) { return x * square(x); }
#   };

# Splats:
race = (winner, runners...) -&gt;
  print winner, runners
#=&gt;race = function() {
#    var runners, winner;
#    winner = arguments[0], runners = 2 &lt;= arguments.length ? __slice.call(arguments, 1) : [];
#    return print(winner, runners);
#  };

# Existence:
alert "I knew it!" if elvis?
#=&gt; if(typeof elvis !== "undefined" &amp;&amp; elvis !== null) { alert("I knew it!"); }

# Array comprehensions:
cubes = (math.cube num for num in list)
#=&gt;cubes = (function() {
#      var _i, _len, _results;
#      _results = [];
#     for (_i = 0, _len = list.length; _i &lt; _len; _i++) {
#          num = list[_i];
#          _results.push(math.cube(num));
#      }
#      return _results;
# })();

foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
#=&gt;foods = ['broccoli', 'spinach', 'chocolate'];
#
#for (_k = 0, _len2 = foods.length; _k &lt; _len2; _k++) {
#  food = foods[_k];
#  if (food !== 'chocolate') {
#    eat(food);
#  }
#}
</code></pre>
<p>Common Lisp:</p>
<pre><code class="lang-plaintext">;;;-----------------------------------------------------------------------------
;;; 0. Syntax
;;;-----------------------------------------------------------------------------

;;; General form

;;; CL has two fundamental pieces of syntax: ATOM and S-EXPRESSION.
;;; Typically, grouped S-expressions are called `forms`.

10            ; an atom; it evaluates to itself
:thing        ; another atom; evaluating to the symbol :thing
t             ; another atom, denoting true
(+ 1 2 3 4)   ; an s-expression
'(4 :foo t)   ; another s-expression


;;; Comments

;;; Single-line comments start with a semicolon; use four for file-level
;;; comments, three for section descriptions, two inside definitions, and one
;;; for single lines. For example,

;;;; life.lisp

;;; Foo bar baz, because quu quux. Optimized for maximum krakaboom and umph.
;;; Needed by the function LINULUKO.

(defun meaning (life)
  "Return the computed meaning of LIFE"
  (let ((meh "abc"))
    ;; Invoke krakaboom
    (loop :for x :across meh
       :collect x)))                    ; store values into x, then return it

;;; Block comments, on the other hand, allow for free-form comments. They are
;;; delimited with #| and |#

#| This is a block comment which
   can span multiple lines and
    #|
       they can be nested!
    |#
|#


;;; Environment

;;; A variety of implementations exist; most are standards-conformant. SBCL
;;; is a good starting point. Third party libraries can be easily installed with
;;; Quicklisp

;;; CL is usually developed with a text editor and a Read Eval Print
;;; Loop (REPL) running at the same time. The REPL allows for interactive
;;; exploration of the program while it is running "live".


;;;-----------------------------------------------------------------------------
;;; 1. Primitive datatypes and operators
;;;-----------------------------------------------------------------------------

;;; Symbols

'foo ; =&gt; FOO  Notice that the symbol is upper-cased automatically.

;;; INTERN manually creates a symbol from a string.

(intern "AAAA")        ; =&gt; AAAA
(intern "aaa")         ; =&gt; |aaa|

;;; Numbers

9999999999999999999999 ; integers
#b111                  ; binary =&gt; 7
#o111                  ; octal =&gt; 73
#x111                  ; hexadecimal =&gt; 273
3.14159s0              ; single
3.14159d0              ; double
1/2                    ; ratios
#C(1 2)                ; complex numbers

;;; Function application are written as (f x y z ...) where f is a function and
;;; x, y, z, ... are the arguments.

(+ 1 2)                ; =&gt; 3

;;; If you want to create literal data, use QUOTE to prevent it from being
;;; evaluated

(quote (+ 1 2))        ; =&gt; (+ 1 2)
(quote a)              ; =&gt; A

;;; The shorthand for QUOTE is '

'(+ 1 2)               ; =&gt; (+ 1 2)
'a                     ; =&gt; A

;;; Basic arithmetic operations

(+ 1 1)                ; =&gt; 2
(- 8 1)                ; =&gt; 7
(* 10 2)               ; =&gt; 20
(expt 2 3)             ; =&gt; 8
(mod 5 2)              ; =&gt; 1
(/ 35 5)               ; =&gt; 7
(/ 1 3)                ; =&gt; 1/3
(+ #C(1 2) #C(6 -4))   ; =&gt; #C(7 -2)

;;; Booleans

t                      ; true; any non-NIL value is true
nil                    ; false; also, the empty list: ()
(not nil)              ; =&gt; T
(and 0 t)              ; =&gt; T
(or 0 nil)             ; =&gt; 0

;;; Characters

#\A                    ; =&gt; #\A
#\λ                    ; =&gt; #\GREEK_SMALL_LETTER_LAMDA
#\u03BB                ; =&gt; #\GREEK_SMALL_LETTER_LAMDA

;;; Strings are fixed-length arrays of characters

"Hello, world!"
"Benjamin \"Bugsy\" Siegel"   ; backslash is an escaping character

;;; Strings can be concatenated

(concatenate 'string "Hello, " "world!") ; =&gt; "Hello, world!"

;;; A string can be treated like a sequence of characters

(elt "Apple" 0) ; =&gt; #\A

;;; FORMAT is used to create formatted output, which ranges from simple string
;;; interpolation to loops and conditionals. The first argument to FORMAT
;;; determines where will the formatted string go. If it is NIL, FORMAT
;;; simply returns the formatted string as a value; if it is T, FORMAT outputs
;;; to the standard output, usually the screen, then it returns NIL.

(format nil "~A, ~A!" "Hello" "world")   ; =&gt; "Hello, world!"
(format t "~A, ~A!" "Hello" "world")     ; =&gt; NIL


;;;-----------------------------------------------------------------------------
;;; 2. Variables
;;;-----------------------------------------------------------------------------

;;; You can create a global (dynamically scoped) variable using DEFVAR and
;;; DEFPARAMETER. The variable name can use any character except: ()",'`;#|\

;;; The difference between DEFVAR and DEFPARAMETER is that re-evaluating a
;;; DEFVAR expression doesn't change the value of the variable. DEFPARAMETER,
;;; on the other hand, does.

;;; By convention, dynamically scoped variables have earmuffs in their name.

(defparameter *some-var* 5)
*some-var* ; =&gt; 5

;;; You can also use unicode characters.
(defparameter *AΛB* nil)

;;; Accessing a previously unbound variable results in an UNBOUND-VARIABLE
;;; error, however it is defined behavior. Don't do it.

;;; You can create local bindings with LET. In the following snippet, `me` is
;;; bound to "dance with you" only within the (let ...). LET always returns
;;; the value of the last `form` in the LET form.

(let ((me "dance with you")) me) ; =&gt; "dance with you"


;;;-----------------------------------------------------------------------------;
;;; 3. Structs and collections
;;;-----------------------------------------------------------------------------;


;;; Structs

(defstruct dog name breed age)
(defparameter *rover*
    (make-dog :name "rover"
              :breed "collie"
              :age 5))
*rover*            ; =&gt; #S(DOG :NAME "rover" :BREED "collie" :AGE 5)
(dog-p *rover*)    ; =&gt; T
(dog-name *rover*) ; =&gt; "rover"

;;; DOG-P, MAKE-DOG, and DOG-NAME are all automatically created by DEFSTRUCT


;;; Pairs

;;; CONS constructs pairs. CAR and CDR return the head and tail of a CONS-pair.

(cons 'SUBJECT 'VERB)         ; =&gt; '(SUBJECT . VERB)
(car (cons 'SUBJECT 'VERB))   ; =&gt; SUBJECT
(cdr (cons 'SUBJECT 'VERB))   ; =&gt; VERB


;;; Lists

;;; Lists are linked-list data structures, made of CONS pairs and end with a
;;; NIL (or '()) to mark the end of the list

(cons 1 (cons 2 (cons 3 nil)))     ; =&gt; '(1 2 3)

;;; LIST is a convenience variadic constructor for lists

(list 1 2 3)                       ; =&gt; '(1 2 3)

;;; When the first argument to CONS is an atom and the second argument is a
;;; list, CONS returns a new CONS-pair with the first argument as the first
;;; item and the second argument as the rest of the CONS-pair

(cons 4 '(1 2 3))                  ; =&gt; '(4 1 2 3)

;;; Use APPEND to join lists

(append '(1 2) '(3 4))             ; =&gt; '(1 2 3 4)

;;; Or CONCATENATE

(concatenate 'list '(1 2) '(3 4))  ; =&gt; '(1 2 3 4)

;;; Lists are a very central type, so there is a wide variety of functionality for
;;; them, a few examples:

(mapcar #'1+ '(1 2 3))             ; =&gt; '(2 3 4)
(mapcar #'+ '(1 2 3) '(10 20 30))  ; =&gt; '(11 22 33)
(remove-if-not #'evenp '(1 2 3 4)) ; =&gt; '(2 4)
(every #'evenp '(1 2 3 4))         ; =&gt; NIL
(some #'oddp '(1 2 3 4))           ; =&gt; T
(butlast '(subject verb object))   ; =&gt; (SUBJECT VERB)


;;; Vectors

;;; Vector's literals are fixed-length arrays

#(1 2 3) ; =&gt; #(1 2 3)

;;; Use CONCATENATE to add vectors together

(concatenate 'vector #(1 2 3) #(4 5 6)) ; =&gt; #(1 2 3 4 5 6)


;;; Arrays

;;; Both vectors and strings are special-cases of arrays.

;;; 2D arrays

(make-array (list 2 2))         ; =&gt; #2A((0 0) (0 0))
(make-array '(2 2))             ; =&gt; #2A((0 0) (0 0))
(make-array (list 2 2 2))       ; =&gt; #3A(((0 0) (0 0)) ((0 0) (0 0)))

;;; Caution: the default initial values of MAKE-ARRAY are implementation-defined.
;;; To explicitly specify them:

(make-array '(2) :initial-element 'unset)  ; =&gt; #(UNSET UNSET)

;;; To access the element at 1, 1, 1:

(aref (make-array (list 2 2 2)) 1 1 1)     ;  =&gt; 0
;;; This value is implementation-defined:
;;; NIL on ECL, 0 on SBCL and CCL.

;;; Adjustable vectors

;;; Adjustable vectors have the same printed representation as
;;; fixed-length vector's literals.

(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3)
                                   :adjustable t :fill-pointer t))
*adjvec* ; =&gt; #(1 2 3)

;;; Adding new elements

(vector-push-extend 4 *adjvec*)   ; =&gt; 3
*adjvec*                          ; =&gt; #(1 2 3 4)


;;; Sets, naively, are just lists:

(set-difference '(1 2 3 4) '(4 5 6 7))   ; =&gt; (3 2 1)
(intersection '(1 2 3 4) '(4 5 6 7))     ; =&gt; 4
(union '(1 2 3 4) '(4 5 6 7))            ; =&gt; (3 2 1 4 5 6 7)
(adjoin 4 '(1 2 3 4))                    ; =&gt; (1 2 3 4)

;;; However, you'll need a better data structure than linked lists when working
;;; with larger data sets

;;; Dictionaries are implemented as hash tables.

;;; Create a hash table

(defparameter *m* (make-hash-table))

;;; Set value

(setf (gethash 'a *m*) 1)

;;; Retrieve value

(gethash 'a *m*) ; =&gt; 1, T

;;; CL expressions have the ability to return multiple values.

(values 1 2) ; =&gt; 1, 2

;;; which can be bound with MULTIPLE-VALUE-BIND

(multiple-value-bind (x y)
    (values 1 2)
  (list y x))

; =&gt; '(2 1)

;;; GETHASH is an example of a function that returns multiple values. The first
;;; value it return is the value of the key in the hash table; if the key is
;;; not found it returns NIL.

;;; The second value determines if that key is indeed present in the hash
;;; table. If a key is not found in the table it returns NIL. This behavior
;;; allows us to check if the value of a key is actually NIL.

;;; Retrieving a non-present value returns nil

(gethash 'd *m*) ;=&gt; NIL, NIL

;;; You can provide a default value for missing keys

(gethash 'd *m* :not-found) ; =&gt; :NOT-FOUND

;;; Let's handle the multiple return values here in code.

(multiple-value-bind (a b)
    (gethash 'd *m*)
  (list a b))
; =&gt; (NIL NIL)

(multiple-value-bind (a b)
    (gethash 'a *m*)
  (list a b))
; =&gt; (1 T)


;;;-----------------------------------------------------------------------------
;;; 3. Functions
;;;-----------------------------------------------------------------------------

;;; Use LAMBDA to create anonymous functions. Functions always returns the
;;; value of the last expression. The exact printable representation of a
;;; function varies between implementations.

(lambda () "Hello World") ; =&gt; #&lt;FUNCTION (LAMBDA ()) {1004E7818B}&gt;

;;; Use FUNCALL to call anonymous functions

(funcall (lambda () "Hello World"))   ; =&gt; "Hello World"
(funcall #'+ 1 2 3)                   ; =&gt; 6

;;; A call to FUNCALL is also implied when the lambda expression is the CAR of
;;; an unquoted list

((lambda () "Hello World"))           ; =&gt; "Hello World"
((lambda (val) val) "Hello World")    ; =&gt; "Hello World"

;;; FUNCALL is used when the arguments are known beforehand. Otherwise, use APPLY

(apply #'+ '(1 2 3))   ; =&gt; 6
(apply (lambda () "Hello World") nil) ; =&gt; "Hello World"

;;; To name a function, use DEFUN

(defun hello-world () "Hello World")
(hello-world) ; =&gt; "Hello World"

;;; The () in the definition above is the list of arguments

(defun hello (name) (format nil "Hello, ~A" name))
(hello "Steve") ; =&gt; "Hello, Steve"

;;; Functions can have optional arguments; they default to NIL

(defun hello (name &amp;optional from)
  (if from
      (format t "Hello, ~A, from ~A" name from)
      (format t "Hello, ~A" name)))

(hello "Jim" "Alpacas")       ; =&gt; Hello, Jim, from Alpacas

;;; The default values can also be specified

(defun hello (name &amp;optional (from "The world"))
   (format nil "Hello, ~A, from ~A" name from))

(hello "Steve")               ; =&gt; Hello, Steve, from The world
(hello "Steve" "the alpacas") ; =&gt; Hello, Steve, from the alpacas

;;; Functions also have keyword arguments to allow non-positional arguments

(defun generalized-greeter (name &amp;key (from "the world") (honorific "Mx"))
  (format t "Hello, ~A ~A, from ~A" honorific name from))

(generalized-greeter "Jim")
; =&gt; Hello, Mx Jim, from the world

(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr")
; =&gt; Hello, Mr Jim, from the alpacas you met last summer


;;;-----------------------------------------------------------------------------
;;; 4. Equality
;;;-----------------------------------------------------------------------------

;;; CL has a sophisticated equality system. Some are covered here.

;;; For numbers, use `='
(= 3 3.0)               ; =&gt; T
(= 2 1)                 ; =&gt; NIL

;;; For object identity (approximately) use EQL
(eql 3 3)               ; =&gt; T
(eql 3 3.0)             ; =&gt; NIL
(eql (list 3) (list 3)) ; =&gt; NIL

;;; for lists, strings, and bit-vectors use EQUAL
(equal (list 'a 'b) (list 'a 'b)) ; =&gt; T
(equal (list 'a 'b) (list 'b 'a)) ; =&gt; NIL


;;;-----------------------------------------------------------------------------
;;; 5. Control Flow
;;;-----------------------------------------------------------------------------

;;; Conditionals

(if t                ; test expression
    "this is true"   ; then expression
    "this is false") ; else expression
; =&gt; "this is true"

;;; In conditionals, all non-NIL values are treated as true

(member 'Groucho '(Harpo Groucho Zeppo)) ; =&gt; '(GROUCHO ZEPPO)
(if (member 'Groucho '(Harpo Groucho Zeppo))
    'yep
    'nope)
; =&gt; 'YEP

;;; COND chains a series of tests to select a result
(cond ((&gt; 2 2) (error "wrong!"))
      ((&lt; 2 2) (error "wrong again!"))
      (t 'ok)) ; =&gt; 'OK

;;; TYPECASE switches on the type of the value
(typecase 1
  (string :string)
  (integer :int))
; =&gt; :int


;;; Looping

;;; Recursion

(defun fact (n)
  (if (&lt; n 2)
      1
    (* n (fact(- n 1)))))

(fact 5) ; =&gt; 120

;;; Iteration

(defun fact (n)
  (loop :for result = 1 :then (* result i)
     :for i :from 2 :to n
     :finally (return result)))

(fact 5) ; =&gt; 120

(loop :for x :across "abcd" :collect x)
; =&gt; (#\a #\b #\c #\d)

(dolist (i '(1 2 3 4))
  (format t "~A" i))
; =&gt; 1234


;;;-----------------------------------------------------------------------------
;;; 6. Mutation
;;;-----------------------------------------------------------------------------

;;; Use SETF to assign a new value to an existing variable. This was
;;; demonstrated earlier in the hash table example.

(let ((variable 10))
    (setf variable 2))
; =&gt; 2

;;; Good Lisp style is to minimize the use of destructive functions and to avoid
;;; mutation when reasonable.


;;;-----------------------------------------------------------------------------
;;; 7. Classes and objects
;;;-----------------------------------------------------------------------------

;;; No more animal classes. Let's have Human-Powered Mechanical
;;; Conveyances.

(defclass human-powered-conveyance ()
  ((velocity
    :accessor velocity
    :initarg :velocity)
   (average-efficiency
    :accessor average-efficiency
   :initarg :average-efficiency))
  (:documentation "A human powered conveyance"))

;;; The arguments to DEFCLASS, in order are:
;;; 1. class name
;;; 2. superclass list
;;; 3. slot list
;;; 4. optional specifiers

;;; When no superclass list is set, the empty list defaults to the
;;; standard-object class. This *can* be changed, but not until you
;;; know what you're doing. Look up the Art of the Metaobject Protocol
;;; for more information.

(defclass bicycle (human-powered-conveyance)
  ((wheel-size
    :accessor wheel-size
    :initarg :wheel-size
    :documentation "Diameter of the wheel.")
   (height
    :accessor height
    :initarg :height)))

(defclass recumbent (bicycle)
  ((chain-type
    :accessor chain-type
    :initarg :chain-type)))

(defclass unicycle (human-powered-conveyance) nil)

(defclass canoe (human-powered-conveyance)
  ((number-of-rowers
    :accessor number-of-rowers
    :initarg :number-of-rowers)))

;;; Calling DESCRIBE on the HUMAN-POWERED-CONVEYANCE class in the REPL gives:

(describe 'human-powered-conveyance)

; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE
;  [symbol]
;
; HUMAN-POWERED-CONVEYANCE names the standard-class #&lt;STANDARD-CLASS
;                                                    HUMAN-POWERED-CONVEYANCE&gt;:
;  Documentation:
;    A human powered conveyance
;  Direct superclasses: STANDARD-OBJECT
;  Direct subclasses: UNICYCLE, BICYCLE, CANOE
;  Not yet finalized.
;  Direct slots:
;    VELOCITY
;      Readers: VELOCITY
;      Writers: (SETF VELOCITY)
;    AVERAGE-EFFICIENCY
;      Readers: AVERAGE-EFFICIENCY
;      Writers: (SETF AVERAGE-EFFICIENCY)

;;; Note the reflective behavior available. CL was designed to be an
;;; interactive system

;;; To define a method, let's find out what our circumference of the
;;; bike wheel turns out to be using the equation: C = d * pi

(defmethod circumference ((object bicycle))
  (* pi (wheel-size object)))

;;; PI is defined as a built-in in CL

;;; Let's suppose we find out that the efficiency value of the number
;;; of rowers in a canoe is roughly logarithmic. This should probably be set
;;; in the constructor/initializer.

;;; To initialize your instance after CL gets done constructing it:

(defmethod initialize-instance :after ((object canoe) &amp;rest args)
  (setf (average-efficiency object)  (log (1+ (number-of-rowers object)))))

;;; Then to construct an instance and check the average efficiency...

(average-efficiency (make-instance 'canoe :number-of-rowers 15))
; =&gt; 2.7725887


;;;-----------------------------------------------------------------------------
;;; 8. Macros
;;;-----------------------------------------------------------------------------

;;; Macros let you extend the syntax of the language. CL doesn't come
;;; with a WHILE loop, however, it's trivial to write one. If we obey our
;;; assembler instincts, we wind up with:

(defmacro while (condition &amp;body body)
    "While `condition` is true, `body` is executed.
`condition` is tested prior to each execution of `body`"
    (let ((block-name (gensym)) (done (gensym)))
        `(tagbody
           ,block-name
           (unless ,condition
               (go ,done))
           (progn
           ,@body)
           (go ,block-name)
           ,done)))

;;; Let's look at the high-level version of this:

(defmacro while (condition &amp;body body)
    "While `condition` is true, `body` is executed.
`condition` is tested prior to each execution of `body`"
  `(loop while ,condition
         do
         (progn
            ,@body)))

;;; However, with a modern compiler, this is not required; the LOOP form
;;; compiles equally well and is easier to read.

;;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator
;;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting"
;;; variables. @ interpolates lists.

;;; GENSYM creates a unique symbol guaranteed to not exist elsewhere in
;;; the system. This is because macros are expanded at compile time and
;;; variables declared in the macro can collide with variables used in
;;; regular code.

;;; See Practical Common Lisp and On Lisp for more information on macros.
</code></pre>
<p>Coq:</p>
<pre><code class="lang-plaintext">(*** Comments ***)

(* Comments are enclosed in (* and *). It's fine to nest comments. *)

(* There are no single-line comments. *)

(*** Variables and functions ***)

(* The Coq proof assistant can be controlled and queried by a command
   language called the vernacular. Vernacular keywords are capitalized and
   the commands end with a period.  Variable and function declarations are
   formed with the Definition vernacular. *)

Definition x := 10.

(* Coq can sometimes infer the types of arguments, but it is common practice
   to annotate with types. *)

Definition inc_nat (x : nat) : nat := x + 1.

(* There exists a large number of vernacular commands for querying
   information.  These can be very useful. *)

Compute (1 + 1). (* 2 : nat *) (* Compute a result. *)

Check tt. (* tt : unit *) (* Check the type of an expressions *)

About plus. (* Prints information about an object *)

(* Print information including the definition *)
Print true. (* Inductive bool : Set := true : Bool | false : Bool *)

Search nat. (* Returns a large list of nat related values *)
Search "_ + _". (* You can also search on patterns *)
Search (?a -&gt; ?a -&gt; bool). (* Patterns can have named parameters  *)
Search (?a * ?a).

(* Locate tells you where notation is coming from. Very helpful when you
   encounter new notation. *)

Locate "+".

(* Calling a function with insufficient number of arguments does not cause
   an error, it produces a new function. *)
Definition make_inc x y := x + y. (* make_inc is nat -&gt; nat -&gt; nat *)
Definition inc_2 := make_inc 2.   (* inc_2 is nat -&gt; nat *)
Compute inc_2 3. (* Evaluates to 5 *)


(* Definitions can be chained with "let ... in" construct.  This is roughly
   the same to assigning values to multiple variables before using them in
   expressions in imperative languages. *)

Definition add_xy : nat := let x := 10 in
                           let y := 20 in
                           x + y.

(* Pattern matching is somewhat similar to switch statement in imperative
   languages, but offers a lot more expressive power. *)

Definition is_zero (x : nat) :=
    match x with
    | 0 =&gt; true
    | _ =&gt; false  (* The "_" pattern means "anything else". *)
    end.

(* You can define recursive function definition using the Fixpoint
   vernacular.*)

Fixpoint factorial n := match n with
                        | 0 =&gt; 1
                        | (S n') =&gt; n * factorial n'
                        end.

(* Function application usually doesn't need parentheses around arguments *)
Compute factorial 5. (* 120 : nat *)

(* ...unless the argument is an expression. *)
Compute factorial (5-1). (* 24 : nat *)

(* You can define mutually recursive functions using "with" *)
Fixpoint is_even (n : nat) : bool := match n with
  | 0 =&gt; true
  | (S n) =&gt; is_odd n
end with
  is_odd n := match n with
  | 0 =&gt; false
  | (S n) =&gt; is_even n
              end.

(* As Coq is a total programming language, it will only accept programs when
   it can understand they terminate. It can be most easily seen when the
   recursive call is on a pattern matched out subpiece of the input, as then
   the input is always decreasing in size. Getting Coq to understand that
   functions terminate is not always easy. See the references at the end of
   the article for more on this topic. *)

(* Anonymous functions use the following syntax: *)

Definition my_square : nat -&gt; nat := fun x =&gt; x * x.

Definition my_id (A : Type) (x : A) : A := x.
Definition my_id2 : forall A : Type, A -&gt; A := fun A x =&gt; x.
Compute my_id nat 3. (* 3 : nat *)

(* You can ask Coq to infer terms with an underscore *)
Compute my_id _ 3.

(* An implicit argument of a function is an argument which can be inferred
   from contextual knowledge. Parameters enclosed in {} are implicit by
   default *)

Definition my_id3 {A : Type} (x : A) : A := x.
Compute my_id3 3. (* 3 : nat *)

(* Sometimes it may be necessary to turn this off. You can make all
   arguments explicit again with @ *)

Compute @my_id3 nat 3.

(* Or give arguments by name *)
Compute my_id3 (A:=nat) 3.

(* Coq has the ability to extract code to OCaml, Haskell, and Scheme *)
Require Extraction.
Extraction Language OCaml.
Extraction "factorial.ml" factorial.
(* The above produces a file factorial.ml and factorial.mli that holds:

type nat =
| O
| S of nat

(** val add : nat -&gt; nat -&gt; nat **)

let rec add n m =
  match n with
  | O -&gt; m
  | S p -&gt; S (add p m)

(** val mul : nat -&gt; nat -&gt; nat **)

let rec mul n m =
  match n with
  | O -&gt; O
  | S p -&gt; add m (mul p m)

(** val factorial : nat -&gt; nat **)

let rec factorial n = match n with
| O -&gt; S O
| S n' -&gt; mul n (factorial n')
*)


(*** Notation ***)

(* Coq has a very powerful Notation system that can be used to write
   expressions in more natural forms. *)

Compute Nat.add 3 4. (* 7 : nat *)
Compute 3 + 4. (* 7 : nat *)

(* Notation is a syntactic transformation applied to the text of the program
   before being evaluated. Notation is organized into notation scopes. Using
   different notation scopes allows for a weak notion of overloading. *)

(* Imports the Zarith module holding definitions related to the integers Z *)

Require Import ZArith.

(* Notation scopes can be opened *)
Open Scope Z_scope.

(* Now numerals and addition are defined on the integers. *)
Compute 1 + 7. (* 8 : Z *)

(* Integer equality checking *)
Compute 1 =? 2. (* false : bool *)

(* Locate is useful for finding the origin and definition of notations *)
Locate "_ =? _". (* Z.eqb x y : Z_scope *)
Close Scope Z_scope.

(* We're back to nat being the default interpretation of "+" *)
Compute 1 + 7. (* 8 : nat *)

(* Scopes can also be opened inline with the shorthand % *)
Compute (3 * -7)%Z. (* -21%Z : Z *)

(* Coq declares by default the following interpretation scopes: core_scope,
   type_scope, function_scope, nat_scope, bool_scope, list_scope, int_scope,
   uint_scope. You may also want the numerical scopes Z_scope (integers) and
   Q_scope (fractions) held in the ZArith and QArith module respectively. *)

(* You can print the contents of scopes *)
Print Scope nat_scope.
(*
Scope nat_scope
Delimiting key is nat
Bound to classes nat Nat.t
"x 'mod' y" := Nat.modulo x y
"x ^ y" := Nat.pow x y
"x ?= y" := Nat.compare x y
"x &gt;= y" := ge x y
"x &gt; y" := gt x y
"x =? y" := Nat.eqb x y
"x &lt;? y" := Nat.ltb x y
"x &lt;=? y" := Nat.leb x y
"x &lt;= y &lt;= z" := and (le x y) (le y z)
"x &lt;= y &lt; z" := and (le x y) (lt y z)
"n &lt;= m" := le n m
"x &lt; y &lt;= z" := and (lt x y) (le y z)
"x &lt; y &lt; z" := and (lt x y) (lt y z)
"x &lt; y" := lt x y
"x / y" := Nat.div x y
"x - y" := Init.Nat.sub x y
"x + y" := Init.Nat.add x y
"x * y" := Init.Nat.mul x y
*)

(* Coq has exact fractions available as the type Q in the QArith module.
   Floating point numbers and real numbers are also available but are a more
   advanced topic, as proving properties about them is rather tricky. *)

Require Import QArith.

Open Scope Q_scope.
Compute 1. (* 1 : Q *)

(* Only 1 and 0 are interpreted as fractions by Q_scope *)
Compute 2. (* 2 : nat *)
Compute (2 # 3). (* The fraction 2/3 *)
Compute (1 # 3) ?= (2 # 6). (* Eq : comparison *)
Close Scope Q_scope.

Compute ( (2 # 3) / (1 # 5) )%Q. (* 10 # 3 : Q *)


(*** Common data structures ***)

(* Many common data types are included in the standard library *)

(* The unit type has exactly one value, tt *)
Check tt. (* tt : unit *)

(* The option type is useful for expressing computations that might fail *)
Compute None. (* None : option ?A *)
Check Some 3. (* Some 3 : option nat *)

(* The type sum A B allows for values of either type A or type B *)
Print sum.
Check inl 3. (* inl 3 : nat + ?B *)
Check inr true. (* inr true : ?A + bool *)
Check sum bool nat. (* (bool + nat)%type : Set *)
Check (bool + nat)%type. (* Notation for sum *)

(* Tuples are (optionally) enclosed in parentheses, items are separated
   by commas. *)
Check (1, true). (* (1, true) : nat * bool *)
Compute prod nat bool. (* (nat * bool)%type : Set *)

Definition my_fst {A B : Type} (x : A * B) : A := match x with
                                                  | (a,b) =&gt; a
                                                  end.

(* A destructuring let is available if a pattern match is irrefutable *)
Definition my_fst2 {A B : Type} (x : A * B) : A := let (a,b) := x in
                                                   a.

(*** Lists ***)

(* Lists are built by using cons and nil or by using notation available in
   list_scope. *)
Compute cons 1 (cons 2 (cons 3 nil)). (*  (1 :: 2 :: 3 :: nil)%list : list nat *)
Compute (1 :: 2 :: 3 :: nil)%list.

(* There is also list notation available in the ListNotations modules *)
Require Import List.
Import ListNotations.
Compute [1 ; 2 ; 3]. (* [1; 2; 3] : list nat *)


(* There is a large number of list manipulation functions available,
   including:

• length
• head : first element (with default)
• tail : all but first element
• app : appending
• rev : reverse
• nth : accessing n-th element (with default)
• map : applying a function
• flat_map : applying a function returning lists
• fold_left : iterator (from head to tail)
• fold_right : iterator (from tail to head)

 *)

Definition my_list : list nat := [47; 18; 34].

Compute List.length my_list. (* 3 : nat *)

(* All functions in coq must be total, so indexing requires a default value *)
Compute List.nth 1 my_list 0. (* 18 : nat *)
Compute List.map (fun x =&gt; x * 2) my_list. (* [94; 36; 68] : list nat *)
Compute List.filter (fun x =&gt; Nat.eqb (Nat.modulo x 2) 0) my_list.
                                               (* [18; 34] : list nat *)
Compute (my_list ++ my_list)%list. (* [47; 18; 34; 47; 18; 34] : list nat *)

(*** Strings ***)

Require Import Strings.String.

(* Use double quotes for string literals. *)
Compute "hi"%string.

Open Scope string_scope.

(* Strings can be concatenated with the "++" operator. *)
Compute String.append "Hello " "World". (* "Hello World" : string *)
Compute "Hello " ++ "World". (* "Hello World" : string *)

(* Strings can be compared for equality *)
Compute String.eqb "Coq is fun!" "Coq is fun!". (* true : bool *)
Compute "no" =? "way". (* false : bool *)

Close Scope string_scope.

(*** Other Modules ***)

(* Other Modules in the standard library that may be of interest:

• Logic : Classical logic and dependent equality
• Arith : Basic Peano arithmetic
• PArith : Basic positive integer arithmetic
• NArith : Basic binary natural number arithmetic
• ZArith : Basic relative integer arithmetic

• Numbers : Various approaches to natural, integer and cyclic numbers
            (currently axiomatically and on top of 2^31 binary words)
• Bool : Booleans (basic functions and results)

• Lists : Monomorphic and polymorphic lists (basic functions and results),
          Streams (infinite sequences defined with co-inductive types)
• Sets : Sets (classical, constructive, finite, infinite, power set, etc.)
• FSets : Specification and implementations of finite sets and finite maps
          (by lists and by AVL trees)
• Reals : Axiomatization of real numbers (classical, basic functions,
          integer part, fractional part, limit, derivative, Cauchy series,
          power series and results,...)
• Relations : Relations (definitions and basic results)
• Sorting : Sorted list (basic definitions and heapsort correctness)
• Strings : 8-bit characters and strings
• Wellfounded : Well-founded relations (basic results)
 *)

(*** User-defined data types ***)

(* Because Coq is dependently typed, defining type aliases is no different
   than defining an alias for a value. *)

Definition my_three : nat := 3.
Definition my_nat : Type := nat.

(* More interesting types can be defined using the Inductive vernacular.
   Simple enumeration can be defined like so *)

Inductive ml := OCaml | StandardML | Coq.
Definition lang := Coq.  (* Has type "ml". *)

(* For more complicated types, you will need to specify the types of the
   constructors. *)

(* Type constructors don't need to be empty. *)
Inductive my_number := plus_infinity
                     | nat_value : nat -&gt; my_number.
Compute nat_value 3. (* nat_value 3 : my_number *)


(* Record syntax is sugar for tuple-like types. It defines named accessor
   functions for the components. Record types are defined with the notation
   {...} *)

Record Point2d (A : Set) := mkPoint2d { x2 : A ; y2 : A }.
(* Record values are constructed with the notation {|...|} *)
Definition mypoint : Point2d nat :=  {| x2 := 2 ; y2 := 3 |}.
Compute x2 nat mypoint. (* 2 : nat *)
Compute mypoint.(x2 nat). (* 2 : nat *)

(* Types can be parameterized, like in this type for "list of lists of
   anything". 'a can be substituted with any type. *)

Definition list_of_lists a := list (list a).
Definition list_list_nat := list_of_lists nat.

(* Types can also be recursive. Like in this type analogous to
   built-in list of naturals. *)

Inductive my_nat_list :=
  EmptyList | NatList : nat -&gt; my_nat_list -&gt; my_nat_list.

Compute NatList 1 EmptyList. (*  NatList 1 EmptyList : my_nat_list *)

(** Matching type constructors **)

Inductive animal := Dog : string -&gt; animal | Cat : string -&gt; animal.

Definition say x :=
    match x with
    | Dog x =&gt; (x ++ " says woof")%string
    | Cat x =&gt; (x ++ " says meow")%string
    end.

Compute say (Cat "Fluffy"). (* "Fluffy says meow". *)

(** Traversing data structures with pattern matching **)

(* Recursive types can be traversed with pattern matching easily.
   Let's see how we can traverse a data structure of the built-in list type.
   Even though the built-in cons ("::") looks like an infix operator,
   it's actually a type constructor and can be matched like any other. *)
Fixpoint sum_list l :=
    match l with
    | [] =&gt; 0
    | head :: tail =&gt; head + (sum_list tail)
    end.

Compute sum_list [1; 2; 3]. (* Evaluates to 6 *)


(*** A Taste of Proving ***)

(* Explaining the proof language is out of scope for this tutorial, but here
   is a taste to whet your appetite. Check the resources below for more. *)

(* A fascinating feature of dependently type based theorem provers is that
   the same primitive constructs underly the proof language as the
   programming features.  For example, we can write and prove the
   proposition A and B implies A in raw Gallina *)

Definition my_theorem : forall A B, A /\ B -&gt; A :=
  fun A B ab =&gt; match ab with
                  | (conj a b) =&gt; a
                end.

(* Or we can prove it using tactics. Tactics are a macro language to help
   build proof terms in a more natural style and automate away some
   drudgery. *)

Theorem my_theorem2 : forall A B, A /\ B -&gt; A.
Proof.
  intros A B ab.  destruct ab as [ a b ]. apply a.
Qed.

(* We can easily prove simple polynomial equalities using the
   automated tactic ring. *)

Require Import Ring.
Require Import Arith.
Theorem simple_poly : forall (x : nat), (x + 1) * (x + 2) = x * x + 3 * x + 2.
  Proof. intros. ring. Qed.

(* Here we prove the closed form for the sum of all numbers 1 to n using
   induction *)

Fixpoint sumn (n : nat) : nat :=
  match n with
  | 0 =&gt; 0
  | (S n') =&gt; n + (sumn n')
  end.

Theorem sum_formula : forall n, 2 * (sumn n) = (n + 1) * n.
Proof. intros n. induction n.
       - reflexivity. (* 0 = 0 base case *)
       - simpl. ring [IHn]. (* induction step *)
Qed.
</code></pre>
<p>Crystal:</p>
<pre><code class="lang-plaintext"># This is a comment

# Everything is an object
nil.class  #=&gt; Nil
100.class  #=&gt; Int32
true.class #=&gt; Bool

# Falsey values are: nil, false and null pointers
!nil   #=&gt; true  : Bool
!false #=&gt; true  : Bool
!0     #=&gt; false : Bool

# Integers

1.class #=&gt; Int32

# Five signed integer types
1_i8.class   #=&gt; Int8
1_i16.class  #=&gt; Int16
1_i32.class  #=&gt; Int32
1_i64.class  #=&gt; Int64
1_i128.class #=&gt; Int128

# Five unsigned integer types
1_u8.class   #=&gt; UInt8
1_u16.class  #=&gt; UInt16
1_u32.class  #=&gt; UInt32
1_u64.class  #=&gt; UInt64
1_u128.class #=&gt; UInt128

2147483648.class          #=&gt; Int64
9223372036854775808.class #=&gt; UInt64

# Binary numbers
0b1101 #=&gt; 13 : Int32

# Octal numbers
0o123 #=&gt; 83 : Int32

# Hexadecimal numbers
0xFE012D #=&gt; 16646445 : Int32
0xfe012d #=&gt; 16646445 : Int32

# Floats

1.0.class #=&gt; Float64

# There are two floating point types
1.0_f32.class #=&gt; Float32
1_f32.class   #=&gt; Float32

1e10.class    #=&gt; Float64
1.5e10.class  #=&gt; Float64
1.5e-7.class  #=&gt; Float64

# Chars use 'a' pair of single quotes

'a'.class #=&gt; Char

# Chars are 32-bit unicode
'あ' #=&gt; 'あ' : Char

# Unicode codepoint
'\u0041' #=&gt; 'A' : Char

# Strings use a "pair" of double quotes

"s".class #=&gt; String

# Strings are immutable
s = "hello, "  #=&gt; "hello, "        : String
s.object_id    #=&gt; 134667712        : UInt64
s += "Crystal"
s              #=&gt; "hello, Crystal" : String
s.object_id    #=&gt; 142528472        : UInt64

# Supports interpolation
"sum = #{1 + 2}" #=&gt; "sum = 3" : String

# Multiline string
"This is
   multiline string" #=&gt; "This is\n   multiline string"


# String with double quotes
%(hello "world") #=&gt; "hello \"world\""

# Symbols
# Immutable, reusable constants represented internally as Int32 integer value.
# They're often used instead of strings to efficiently convey specific,
# meaningful values

:symbol.class #=&gt; Symbol

sentence = :question?     # :"question?" : Symbol

sentence == :question?    #=&gt; true  : Bool
sentence == :exclamation! #=&gt; false : Bool
sentence == "question?"   #=&gt; false : Bool

# Arrays

[1, 2, 3].class         #=&gt; Array(Int32)
[1, "hello", 'x'].class #=&gt; Array(Char | Int32 | String)

# Empty arrays should specify a type
[]               # Syntax error: for empty arrays use '[] of ElementType'
[] of Int32      #=&gt; [] : Array(Int32)
Array(Int32).new #=&gt; [] : Array(Int32)

# Arrays can be indexed
array = [1, 2, 3, 4, 5] #=&gt; [1, 2, 3, 4, 5] : Array(Int32)
array[0]                #=&gt; 1               : Int32
array[10]               # raises IndexError
array[-6]               # raises IndexError
array[10]?              #=&gt; nil             : (Int32 | Nil)
array[-6]?              #=&gt; nil             : (Int32 | Nil)

# From the end
array[-1] #=&gt; 5

# With a start index and size
array[2, 3] #=&gt; [3, 4, 5]

# Or with range
array[1..3] #=&gt; [2, 3, 4]

# Add to an array
array &lt;&lt; 6  #=&gt; [1, 2, 3, 4, 5, 6]

# Remove from the end of the array
array.pop #=&gt; 6
array     #=&gt; [1, 2, 3, 4, 5]

# Remove from the beginning of the array
array.shift #=&gt; 1
array       #=&gt; [2, 3, 4, 5]

# Check if an item exists in an array
array.includes? 3 #=&gt; true

# Special syntax for an array of string and an array of symbols
%w(one two three) #=&gt; ["one", "two", "three"] : Array(String)
%i(one two three) #=&gt; [:one, :two, :three]    : Array(Symbol)

# There is a special array syntax with other types too, as long as
# they define a .new and a #&lt;&lt; method
set = Set{1, 2, 3} #=&gt; Set{1, 2, 3}
set.class          #=&gt; Set(Int32)

# The above is equivalent to
set = Set(typeof(1, 2, 3)).new #=&gt; Set{} : Set(Int32)
set &lt;&lt; 1                       #=&gt; Set{1} : Set(Int32)
set &lt;&lt; 2                       #=&gt; Set{1, 2} : Set(Int32)
set &lt;&lt; 3                       #=&gt; Set{1, 2, 3} : Set(Int32)

# Hashes

{1 =&gt; 2, 3 =&gt; 4}.class   #=&gt; Hash(Int32, Int32)
{1 =&gt; 2, 'a' =&gt; 3}.class #=&gt; Hash(Char| Int32, Int32)

# Empty hashes must specify a type
{}                     # Syntax Error: for empty hashes use '{} of KeyType =&gt; ValueType'
{} of Int32 =&gt; Int32   # {} : Hash(Int32, Int32)
Hash(Int32, Int32).new # {} : Hash(Int32, Int32)

# Hashes can be quickly looked up by key
hash = {"color" =&gt; "green", "number" =&gt; 5}
hash["color"]        #=&gt; "green"
hash["no_such_key"]  #=&gt; Missing hash key: "no_such_key" (KeyError)
hash["no_such_key"]? #=&gt; nil

# The type of the returned value is based on all key types
hash["number"] #=&gt; 5 : (Int32 | String)

# Check existence of keys hash
hash.has_key? "color" #=&gt; true

# Special notation for symbol and string keys
{key1: 'a', key2: 'b'}     # {:key1 =&gt; 'a', :key2 =&gt; 'b'}
{"key1": 'a', "key2": 'b'} # {"key1" =&gt; 'a', "key2" =&gt; 'b'}

# Special hash literal syntax with other types too, as long as
# they define a .new and a #[]= methods
class MyType
  def []=(key, value)
    puts "do stuff"
  end
end

MyType{"foo" =&gt; "bar"}

# The above is equivalent to
tmp = MyType.new
tmp["foo"] = "bar"
tmp

# Ranges

1..10                  #=&gt; Range(Int32, Int32)
Range.new(1, 10).class #=&gt; Range(Int32, Int32)

# Can be inclusive or exclusive
(3..5).to_a  #=&gt; [3, 4, 5]
(3...5).to_a #=&gt; [3, 4]

# Check whether range includes the given value or not
(1..8).includes? 2 #=&gt; true

# Tuples are a fixed-size, immutable, stack-allocated sequence of values of
# possibly different types.
{1, "hello", 'x'}.class #=&gt; Tuple(Int32, String, Char)

# Access tuple's value by its index
tuple = {:key1, :key2}
tuple[1] #=&gt; :key2
tuple[2] #=&gt; Error: index out of bounds for Tuple(Symbol, Symbol) (2 not in -2..1)

# Can be expanded into multiple variables
a, b, c = {:a, 'b', "c"}
a #=&gt; :a
b #=&gt; 'b'
c #=&gt; "c"

# Procs represent a function pointer with an optional context (the closure data)
# It is typically created with a proc literal
proc = -&gt;(x : Int32) { x.to_s }
proc.class # Proc(Int32, String)
# Or using the new method
Proc(Int32, String).new { |x| x.to_s }

# Invoke proc with call method
proc.call 10 #=&gt; "10"

# Control statements

if true
  "if statement"
elsif false
  "else-if, optional"
else
  "else, also optional"
end 

puts "if as a suffix" if true

# If as an expression
a = if 2 &gt; 1
      3
    else
      4
    end

a #=&gt; 3

# Ternary if
a = 1 &gt; 2 ? 3 : 4 #=&gt; 4

# Case statement
cmd = "move"

action = case cmd
  when "create"
    "Creating..."
  when "copy"
    "Copying..."
  when "move"
    "Moving..."
  when "delete"
    "Deleting..."
end

action #=&gt; "Moving..."

# Loops
index = 0
while index &lt;= 3
  puts "Index: #{index}"
  index += 1
end
# Index: 0
# Index: 1
# Index: 2
# Index: 3

index = 0
until index &gt; 3
  puts "Index: #{index}"
  index += 1
end
# Index: 0
# Index: 1
# Index: 2
# Index: 3

# But the preferable way is to use each
(1..3).each do |index|
  puts "Index: #{index}"
end
# Index: 1
# Index: 2
# Index: 3

# Variable's type depends on the type of the expression
# in control statements
if a &lt; 3
  a = "hello"
else
  a = true
end
typeof(a) #=&gt; (Bool | String)

if a &amp;&amp; b
  # here both a and b are guaranteed not to be Nil
end

if a.is_a? String
  a.class #=&gt; String
end

# Functions

def double(x)
  x * 2
end

# Functions (and all blocks) implicitly return the value of the last statement
double(2) #=&gt; 4

# Parentheses are optional where the call is unambiguous
double 3 #=&gt; 6

double double 3 #=&gt; 12

def sum(x, y)
  x + y
end

# Method arguments are separated by a comma
sum 3, 4 #=&gt; 7

sum sum(3, 4), 5 #=&gt; 12

# yield
# All methods have an implicit, optional block parameter
# it can be called with the 'yield' keyword

def surround
  puts '{'
  yield
  puts '}'
end

surround { puts "hello world" }

# {
# hello world
# }


# You can pass a block to a function
# "&amp;" marks a reference to a passed block
def guests(&amp;block)
  block.call "some_argument"
end

# You can pass a list of arguments, which will be converted into an array
# That's what splat operator ("*") is for
def guests(*array)
  array.each { |guest| puts guest }
end

# If a method returns an array, you can use destructuring assignment
def foods
    ["pancake", "sandwich", "quesadilla"]
end
breakfast, lunch, dinner = foods
breakfast #=&gt; "pancake"
dinner    #=&gt; "quesadilla"

# By convention, all methods that return booleans end with a question mark
5.even? # false
5.odd?  # true

# Also by convention, if a method ends with an exclamation mark, it does 
# something destructive like mutate the receiver.
# Some methods have a ! version to make a change, and
# a non-! version to just return a new changed version
fruits = ["grapes", "apples", "bananas"]
fruits.sort  #=&gt; ["apples", "bananas", "grapes"]
fruits       #=&gt; ["grapes", "apples", "bananas"]
fruits.sort! #=&gt; ["apples", "bananas", "grapes"]
fruits       #=&gt; ["apples", "bananas", "grapes"]

# However, some mutating methods do not end in !
fruits.shift #=&gt; "apples"
fruits       #=&gt; ["bananas", "grapes"]

# Define a class with the class keyword
class Human

  # A class variable. It is shared by all instances of this class.
  @@species = "H. sapiens"

  # An instance variable. Type of name is String
  @name : String

  # Basic initializer
  # Assign the argument to the "name" instance variable for the instance
  # If no age given, we will fall back to the default in the arguments list.
  def initialize(@name, @age = 0)
  end

  # Basic setter method
  def name=(name)
    @name = name
  end

  # Basic getter method
  def name
    @name
  end

  # The above functionality can be encapsulated using the propery method as follows
  property :name

  # Getter/setter methods can also be created individually like this
  getter :name
  setter :name

  # A class method uses self to distinguish from instance methods.
  # It can only be called on the class, not an instance.
  def self.say(msg)
    puts msg
  end

  def species
    @@species
  end
end


# Instantiate a class
jim = Human.new("Jim Halpert")

dwight = Human.new("Dwight K. Schrute")

# Let's call a couple of methods
jim.species #=&gt; "H. sapiens"
jim.name #=&gt; "Jim Halpert"
jim.name = "Jim Halpert II" #=&gt; "Jim Halpert II"
jim.name #=&gt; "Jim Halpert II"
dwight.species #=&gt; "H. sapiens"
dwight.name #=&gt; "Dwight K. Schrute"

# Call the class method
Human.say("Hi") #=&gt; print Hi and returns nil

# Variables that start with @ have instance scope
class TestClass
  @var = "I'm an instance var"
end

# Variables that start with @@ have class scope
class TestClass
  @@var = "I'm a class var"
end
# Variables that start with a capital letter are constants
Var = "I'm a constant"
Var = "can't be updated" # Error: already initialized constant Var

# Class is also an object in Crystal. So a class can have instance variables.
# Class variable is shared among the class and all of its descendants.

# base class
class Human
  @@foo = 0

  def self.foo
    @@foo
  end

  def self.foo=(value)
    @@foo = value
  end
end

# derived class
class Worker &lt; Human
end

Human.foo   #=&gt; 0
Worker.foo  #=&gt; 0

Human.foo = 2 #=&gt; 2
Worker.foo    #=&gt; 0

Worker.foo = 3 #=&gt; 3
Human.foo   #=&gt; 2
Worker.foo  #=&gt; 3

module ModuleExample
  def foo
    "foo"
  end
end

# Including modules binds their methods to the class instances
# Extending modules binds their methods to the class itself

class Person
  include ModuleExample
end

class Book
  extend ModuleExample
end

Person.foo     # =&gt; undefined method 'foo' for Person:Class
Person.new.foo # =&gt; 'foo'
Book.foo       # =&gt; 'foo'
Book.new.foo   # =&gt; undefined method 'foo' for Book


# Exception handling

# Define new exception
class MyException &lt; Exception
end

# Define another exception
class MyAnotherException &lt; Exception; end

ex = begin
   raise MyException.new
rescue ex1 : IndexError
  "ex1"
rescue ex2 : MyException | MyAnotherException
  "ex2"
rescue ex3 : Exception
  "ex3"
rescue ex4 # catch any kind of exception
  "ex4"
end

ex #=&gt; "ex2"
</code></pre>
<p>Dart:</p>
<pre><code class="lang-plaintext">import "dart:collection";
import "dart:math" as math;

/// Welcome to Learn Dart in 15 minutes. http://dart.dev/
/// This is an executable tutorial. You can run it with Dart or on
/// the Try Dart! site if you copy/paste it there. http://dartpad.dev/
/// You can also run Flutter in DartPad by click the `&lt; &gt; New Pad ` and choose Flutter


/// In Dart, Everything is an Object.
/// Every declaration of an object is an instance of Null and
/// Null is also an object.


/// 3 Types of comments in dart
// Single line comment
/**
* Multi-line comment
* Can comment several lines
*/
/// Code doc comment
/// It uses markdown syntax to generate code docs when making an API.
/// Code doc comment is the recommended choice when documenting your APIs, classes and methods.

/// 4 types of variable declaration.
/// Constants are variables that are immutable cannot be change or altered.
/// `const` in dart should practice SCREAMING_SNAKE_CASE name declaration.
const CONSTANT_VALUE = "I CANNOT CHANGE";
CONSTANT_VALUE = "DID I?"; //Error
/// Final is another variable declaration that cannot be change once it has been instantiated. Commonly used in classes and functions
/// `final` can be declared in pascalCase.
final finalValue = "value cannot be changed once instantiated";
finalValue = "Seems not"; //Error

/// `var` is another variable declaration that is mutable and can change its value. Dart will infer types and will not change its data type
var mutableValue = "Variable string";
mutableValue = "this is valid";
mutableValue = false; // Error.

/// `dynamic` is another variable declaration in which the type is not evaluated by the dart static type checking.
/// It can change its value and data type.
/// Some dartisans uses dynamic cautiously as it cannot keep track of its data type. so use it at your own risk
dynamic dynamicValue = "I'm a string";
dynamicValue = false; // false


/// Functions can be declared in a global space
/// Function declaration and method declaration look the same. Function
/// declarations can be nested. The declaration takes the form of
/// name() {} or name() =&gt; singleLineExpression;
/// The fat arrow function declaration can be an implicit or
/// explicit return for the result of the expression.
/// Dart will execute a function called `main()` anywhere in the dart project.
///
example1() {
  nested1() {
    nested2() =&gt; print("Example1 nested 1 nested 2");
    nested2();
  }

  nested1();
}

/// Anonymous functions don't include a name
example2() {
  //// Explicit return type.
  nested1(void Function() fn) {
    fn();
  }
  nested1(() =&gt; print("Example2 nested 1"));
}

/// When a function parameter is declared, the declaration can include the
/// number of parameters the function takes by explicitly specifying the names of the
/// parameters it takes.
example3() {
  planA(fn(String informSomething)) {
    fn("Example3 plan A");
  }
  planB(fn) {
    // Or don't declare number of parameters.
    fn("Example3 plan B");
  }

  planA((s) =&gt; print(s));
  planB((s) =&gt; print(s));
}

/// Functions have closure access to outer variables.
/// Dart will infer types when the variable has a value of something.
/// In this example dart knows that this variable is a String.
var example4Something = "Example4 nested 1";
example4() {
  nested1(fn(informSomething)) {
    fn(example4Something);
  }

  nested1((s) =&gt; print(s));
}

/// Class declaration with a sayIt method, which also has closure access
/// to the outer variable as though it were a function as seen before.
var example5method = "Example5 sayIt";

class Example5Class {
  sayIt() {
    print(example5method);
  }
}

example5() {
  /// Create an anonymous instance of the Example5Class and call the sayIt
  /// method on it.
  /// the `new` keyword is optional in Dart.
  new Example5Class().sayIt();
}

/// Class declaration takes the form of class name { [classBody] }.
/// Where classBody can include instance methods and variables, but also
/// class methods and variables.
class Example6Class {
  var instanceVariable = "Example6 instance variable";
  sayIt() {
    print(instanceVariable);
  }
}

example6() {
   Example6Class().sayIt();
}

/// Class methods and variables are declared with "static" terms.
class Example7Class {
  static var classVariable = "Example7 class variable";
  static sayItFromClass() {
    print(classVariable);
  }

  sayItFromInstance() {
    print(classVariable);
  }
}

example7() {
  Example7Class.sayItFromClass();
  new Example7Class().sayItFromInstance();
}

/// Dart supports Generics.
/// Generics refers to the technique of writing the code for a class
/// without specifying the data type(s) that the class works on.
/// Source: https://stackoverflow.com/questions/4560890/what-are-generics-in-c

/// Type `T` refers to any type that has been instantiated
/// you can call whatever you want
/// Programmers uses the convention in the following
/// T - Type(used for class and primitype types)
/// E - Element(used for List, Set, or Iterable)
/// K,V - Key Value(used for Map)
class GenericExample&lt;T&gt;{
  void printType(){
    print("$T")
  }
  // methods can also have generics
  genericMethod&lt;M&gt;(){
    print("class:$T, method: $M");
  }
}


/// List are similar to arrays but list is a child of Iterable&lt;E&gt;
/// Therefore Maps, List, LinkedList are all child of Iterable&lt;E&gt; to be able to loop using the keyword `for`
/// Important things to remember:
/// () - Iterable&lt;E&gt;
/// [] - List&lt;E&gt;
/// {} - Map&lt;K,V&gt;


/// List are great, but there's a restriction for what List can be
/// outside of function/method bodies. List on the outer scope of class
/// or outside of class have to be constant. Strings and numbers are constant
/// by default. But arrays and maps are not. They can be made constant by
/// declaring them "const". Kind of similar to JavaScript's Object.freeze()
const example8List = ["Example8 const array"];
const  example8Map = {"someKey": "Example8 const map"};
/// Declare List or Maps as Objects.
 List&lt;String&gt; explicitList = new List&lt;String&gt;();
 Map&lt;String,dynamic&gt; explicitMaps = new Map&lt;String,dynamic&gt;();

 explicitList.add("SomeArray");
example8() {
  print(example8Map["someKey"]);
  print(explicitList[0]);
}

/// Assigning a list from one variable to another will not be the same result.
/// Because dart is pass-reference-by-value.
/// So when you assign an existing list to a new variable.
/// Instead of List, it becomes an Iterable
var iterableExplicitList = explicitList;
print(iterableExplicitList) // ("SomeArray"); "[]" becomes "()"
var newExplicitLists = explicitList.toList() // Converts Iterable&lt;E&gt; to List&lt;E&gt;

/// Loops in Dart take the form of standard for () {} or while () {} loops,
/// slightly more modern for (.. in ..) {}, or functional callbacks with many
/// supported features, starting with forEach,map and where.
var example9Array = const ["a", "b"];
example9() {
  for (int i = 0; i &lt; example9Array.length; i++) {
    print("Example9 for loop '${example9Array[i]}'");
  }
  var i = 0;
  while (i &lt; example9Array.length) {
    print("Example9 while loop '${example9Array[i]}'");
    i++;
  }
  for (final e in example9Array) {
    print("Example9 for-in loop '${e}'");
  }

  example9Array.forEach((e) =&gt; print("Example9 forEach loop '${e}'"));

}

/// To loop over the characters of a string or to extract a substring.
var example10String = "ab";
example10() {
  for (var i = 0; i &lt; example10String.length; i++) {
    print("Example10 String character loop '${example10String[i]}'");
  }
  for (var i = 0; i &lt; example10String.length; i++) {
    print("Example10 substring loop '${example10String.substring(i, i + 1)}'");
  }
}

/// `int`, `double`  and `num` are the three supported number formats.
/// `num` can be either `int` or `double`.
/// `int` and `double` are children of type `num`
example11() {
  var i = 1 + 320, d = 3.2 + 0.01;
  final num myFinalNumDouble = 2.2;
  final num myFinalNumInt = 2;
  final int myFinalInt = 1;
  final double myFinalDouble = 0.1;
  num myNumDouble = 2.2;
  num myNumInt = 2;
  int myInt = 1;
  double myDouble = 0; // Dart will add decimal prefix, becomes 0.0;
  myNumDouble = myFinalInt; // valid
  myNumDouble = myFinalDouble; // valid
  myNumDouble = myFinalNumInt; // valid

  myNumInt = myFinalInt; // valid
  myNumInt = myFinalDouble; // valid
  myNumInt = myFinalNumDouble; // valid

  myInt = myNumDouble; // error
  myInt = myFinalDouble; // error
  myInt = myFinalNumInt; // valid

  myDouble = myFinalInt; // error
  myDouble = myFinalNumInt; // error
  myDouble = myFinalNumDouble; // valid

  print("Example11 int ${i}");
  print("Example11 double ${d}");

}

/// DateTime provides date/time arithmetic.
example12() {
  var now = new DateTime.now();
  print("Example12 now '${now}'");
  now = now.add(new Duration(days: 1));
  print("Example12 tomorrow '${now}'");
}

/// Regular expressions are supported.
example13() {
  var s1 = "some string", s2 = "some", re = new RegExp("^s.+?g\$");
  match(s) {
    if (re.hasMatch(s)) {
      print("Example13 regexp matches '${s}'");
    } else {
      print("Example13 regexp doesn't match '${s}'");
    }
  }

  match(s1);
  match(s2);
}

/// Boolean expressions support implicit conversions and dynamic type
example14() {
  var a = true;
  if (a) {
    print("true, a is $a");
  }
  a = false;
  if (a) {
    print("true, a is $a"); 
  } else {
    print("false, a is $a"); /// runs here
  }

  /// dynamic typed null can not be convert to bool
  var b; /// b is dynamic type
  b = "abc";
  try {
    if (b) {
      print("true, b is $b");
    } else {
      print("false, b is $b");
    }
  } catch (e) {
    print("error, b is $b"); /// this could be run but got error
  }
  b = null; 
  if (b) { /// Failed assertion: boolean expression must not be null)
    print("true, b is $b");
  } else {
    print("false, b is $b"); 
  }

  /// statically typed null can not be convert to bool
  var c = "abc";
  c = null;
  /// compilation failed
  /// if (c) {
  ///   print("true, c is $c");
  /// } else {
  ///   print("false, c is $c");
  /// }
}

/// try/catch/finally and throw are used for exception handling.
/// throw takes any object as parameter;
example15() {
  try {
    try {
      throw "Some unexpected error.";
    } catch (e) {
      print("Example15 an exception: '${e}'");
      throw e; /// Re-throw
    }
  } catch (e) {
    print("Example15 catch exception being re-thrown: '${e}'");
  } finally {
    print("Example15 Still run finally");
  }
}

/// To be efficient when creating a long string dynamically, use
/// StringBuffer. Or you could join a string array.
example16() {
  var sb = new StringBuffer(), a = ["a", "b", "c", "d"], e;
  for (e in a) {
    sb.write(e);
  }
  print("Example16 dynamic string created with "
      "StringBuffer '${sb.toString()}'");
  print("Example16 join string array '${a.join()}'");
}

/// Strings can be concatenated by just having string List next to
/// one another with no further operator needed.

example17() {
  print("Example17 "
      "concatenate "
      "strings "
      "just like that");
}

/// Strings have single-quote or double-quote for delimiters with no
/// actual difference between the two. The given flexibility can be good
/// to avoid the need to escape content that matches the delimiter being
/// used. For example, double-quotes of HTML attributes if the string
/// contains HTML content.
example18() {
  print('Example18 &lt;a href="etc"&gt;'
      "Don't can't I'm Etc"
      '&lt;/a&gt;');
}

/// Strings with triple single-quotes or triple double-quotes span
/// multiple lines and include line delimiters.
example19() {
  print('''Example19 &lt;a href="etc"&gt;
Example19 Don't can't I'm Etc
Example19 &lt;/a&gt;''');
}

/// Strings have the nice interpolation feature with the $ character.
/// With $ { [expression] }, the return of the expression is interpolated.
/// $ followed by a variable name interpolates the content of that variable.
/// $ can be escaped like so \$ to just add it to the string instead.
example20() {
  var s1 = "'\${s}'", s2 = "'\$s'";
  print("Example20 \$ interpolation ${s1} or $s2 works.");
}

/// Optional types allow for the annotation of APIs and come to the aid of
/// IDEs so the IDEs can better refactor, auto-complete and check for
/// errors. So far we haven't declared any types and the programs have
/// worked just fine. In fact, types are disregarded during runtime.
/// Types can even be wrong and the program will still be given the
/// benefit of the doubt and be run as though the types didn't matter.
/// There's a runtime parameter that checks for type errors which is
/// the checked mode, which is said to be useful during development time,
/// but which is also slower because of the extra checking and is thus
/// avoided during deployment runtime.
class Example21 {
  List&lt;String&gt; _names;
  Example21() {
    _names = ["a", "b"];
  }
  List&lt;String&gt; get names =&gt; _names;
  set names(List&lt;String&gt; list) {
    _names = list;
  }

  int get length =&gt; _names.length;
  void add(String name) {
    _names.add(name);
  }
}

void example21() {
  Example21 o = new Example21();
  o.add("c");
  print("Example21 names '${o.names}' and length '${o.length}'");
  o.names = ["d", "e"];
  print("Example21 names '${o.names}' and length '${o.length}'");
}

/// Class inheritance takes the form of class name extends AnotherClassName {}.
class Example22A {
  var _name = "Some Name!";
  get name =&gt; _name;
}

class Example22B extends Example22A {}

example22() {
  var o = new Example22B();
  print("Example22 class inheritance '${o.name}'");
}

/// Class mixin is also available, and takes the form of
/// class name extends SomeClass with AnotherClassName {}.
/// It's necessary to extend some class to be able to mixin another one.
/// The template class of mixin cannot at the moment have a constructor.
/// Mixin is mostly used to share methods with distant classes, so the
/// single inheritance doesn't get in the way of reusable code.
/// Mixins follow the "with" statement during the class declaration.
class Example23A {}

class Example23Utils {
  addTwo(n1, n2) {
    return n1 + n2;
  }
}

class Example23B extends Example23A with Example23Utils {
  addThree(n1, n2, n3) {
    return addTwo(n1, n2) + n3;
  }
}

example23() {
  var o = new Example23B(), r1 = o.addThree(1, 2, 3), r2 = o.addTwo(1, 2);
  print("Example23 addThree(1, 2, 3) results in '${r1}'");
  print("Example23 addTwo(1, 2) results in '${r2}'");
}

/// The Class constructor method uses the same name of the class and
/// takes the form of SomeClass() : super() {}, where the ": super()"
/// part is optional and it's used to delegate constant parameters to the
/// super-parent's constructor.
class Example24A {
  var _value;
  Example24A({value: "someValue"}) {
    _value = value;
  }
  get value =&gt; _value;
}

class Example24B extends Example24A {
  Example24B({value: "someOtherValue"}) : super(value: value);
}

example24() {
  var o1 = new Example24B(), o2 = new Example24B(value: "evenMore");
  print("Example24 calling super during constructor '${o1.value}'");
  print("Example24 calling super during constructor '${o2.value}'");
}

/// There's a shortcut to set constructor parameters in case of simpler classes.
/// Just use the this.parameterName prefix and it will set the parameter on
/// an instance variable of same name.
class Example25 {
  var value, anotherValue;
  Example25({this.value, this.anotherValue});
}

example25() {
  var o = new Example25(value: "a", anotherValue: "b");
  print("Example25 shortcut for constructor '${o.value}' and "
      "'${o.anotherValue}'");
}

/// Named parameters are available when declared between {}.
/// Parameter order can be optional when declared between {}.
/// Parameters can be made optional when declared between [].
example26() {
  var _name, _surname, _email;
  setConfig1({name, surname}) {
    _name = name;
    _surname = surname;
  }

  setConfig2(name, [surname, email]) {
    _name = name;
    _surname = surname;
    _email = email;
  }

  setConfig1(surname: "Doe", name: "John");
  print("Example26 name '${_name}', surname '${_surname}', "
      "email '${_email}'");
  setConfig2("Mary", "Jane");
  print("Example26 name '${_name}', surname '${_surname}', "
      "email '${_email}'");
}

/// Variables declared with final can only be set once.
/// In case of classes, final instance variables can be set via constant
/// constructor parameter.
class Example27 {
  final color1, color2;
  /// A little flexibility to set final instance variables with syntax
  /// that follows the :
  Example27({this.color1, color2}) : color2 = color2;
}

example27() {
  final color = "orange", o = new Example27(color1: "lilac", color2: "white");
  print("Example27 color is '${color}'");
  print("Example27 color is '${o.color1}' and '${o.color2}'");
}

/// To import a library, use import "libraryPath" or if it's a core library,
/// import "dart:libraryName". There's also the "pub" package management with
/// its own convention of import "package:packageName".
/// See import "dart:collection"; at the top. Imports must come before
/// other code declarations. IterableBase comes from dart:collection.
class Example28 extends IterableBase {
  var names;
  Example28() {
    names = ["a", "b"];
  }
  get iterator =&gt; names.iterator;
}

example28() {
  var o = new Example28();
  o.forEach((name) =&gt; print("Example28 '${name}'"));
}

/// For control flow we have:
/// * standard switch with must break statements
/// * if-else if-else and ternary ..?..:.. operator
/// * closures and anonymous functions
/// * break, continue and return statements
example29() {
  var v = true ? 30 : 60;
  switch (v) {
    case 30:
      print("Example29 switch statement");
      break;
  }
  if (v &lt; 30) {
  } else if (v &gt; 30) {
  } else {
    print("Example29 if-else statement");
  }
  callItForMe(fn()) {
    return fn();
  }

  rand() {
    v = new DM.Random().nextInt(50);
    return v;
  }

  while (true) {
    print("Example29 callItForMe(rand) '${callItForMe(rand)}'");
    if (v != 30) {
      break;
    } else {
      continue;
    }
    /// Never gets here.
  }
}

/// Parse int, convert double to int, or just keep int when dividing numbers
/// by using the ~/ operation. Let's play a guess game too.
example30() {
  var gn,
      tooHigh = false,
      n,
      n2 = (2.0).toInt(),
      top = int.parse("123") ~/ n2,
      bottom = 0;
  top = top ~/ 6;
  gn = new DM.Random().nextInt(top + 1); /// +1 because nextInt top is exclusive
  print("Example30 Guess a number between 0 and ${top}");
  guessNumber(i) {
    if (n == gn) {
      print("Example30 Guessed right! The number is ${gn}");
    } else {
      tooHigh = n &gt; gn;
      print("Example30 Number ${n} is too "
          "${tooHigh ? 'high' : 'low'}. Try again");
    }
    return n == gn;
  }

  n = (top - bottom) ~/ 2;
  while (!guessNumber(n)) {
    if (tooHigh) {
      top = n - 1;
    } else {
      bottom = n + 1;
    }
    n = bottom + ((top - bottom) ~/ 2);
  }
}

/// Optional Positional Parameter:
/// parameter will be disclosed with square bracket [ ] &amp; square bracketed parameter are optional.
example31() {
    findVolume31(int length, int breath, [int height]) {
      print('length = $length, breath = $breath, height = $height');
    }

    findVolume31(10,20,30); //valid
    findVolume31(10,20); //also valid
}

/// Optional Named Parameter:
/// parameter will be disclosed with curly bracket { }
/// curly bracketed parameter are optional.
/// have to use parameter name to assign a value which separated with colan :
/// in curly bracketed parameter order does not matter
/// these type parameter help us to avoid confusion while passing value for a function which has many parameter.
example32() {
    findVolume32(int length, int breath, {int height}) {
    print('length = $length, breath = $breath, height = $height');
    }

    findVolume32(10,20,height:30);//valid &amp; we can see the parameter name is mentioned here.
    findVolume32(10,20);//also valid
}

/// Optional Default Parameter:
/// same like optional named parameter in addition we can assign default value for this parameter.
/// which means no value is passed this default value will be taken.
example33() {
    findVolume33(int length, int breath, {int height=10}) {
     print('length = $length, breath = $breath, height = $height');
    }

    findVolume33(10,20,height:30);//valid
    findVolume33(10,20);//valid
}

/// Dart has also added feature such as Null aware operators
var isBool = true;
var hasString = isBool ?? "default String";

/// Programs have only one entry point in the main function.
/// Nothing is expected to be executed on the outer scope before a program
/// starts running with what's in its main function.
/// This helps with faster loading and even lazily loading of just what
/// the program needs to startup with.
main() {
  print("Learn Dart in 15 minutes!");
  [
    example1, example2, example3, example4, example5,
    example6, example7, example8, example9, example10,
    example11, example12, example13, example14, example15,
    example16, example17, example18, example19, example20,
    example21, example22, example23, example24, example25,
    example26, example27, example28, example29,
    example30 // Adding this comment stops the dart formatter from putting all items on a new line
  ].forEach((ef) =&gt; ef());
}
</code></pre>
<p>Dhall:</p>
<pre><code class="lang-plaintext">-- Single-line comment

{- Multi-line comment

   Unicode is fine 🙂

   This file is a valid Dhall expression that evaluates to a large record
   collecting the results of each step.

   You can view the results by interpreting the file:

       $ dhall --file learndhall.dhall

   {- Comments can be nested -}
-}

let greeting = "Hello, world!"

let fruits = "🍋🍓🍍🍉🍌"

let interpolation = "Enjoy some delicious fruit: ${fruits}"

let multilineText {- Inline comments work, too -} =
        ''
        Leading whitespace is stripped from multi-line text literals.

        That means you can freely indent or dedent a text literal without
        changing the result.

            Relative indentation within the literal is still preserved.

        Other than that, the text literal is preserved verbatim, similar to a
        "literal" YAML multiline string.
        ''

let bool = True

-- Type annotations on bindings are optional, but helpful, so we'll use them
let annotation : Bool = True

let renderedBool : Text = if bool then "True" else "False"

-- Natural numbers are non-negative and are unsigned
let naturalNumber : Natural = 42

-- Integers may be negative, but require an explicit sign, even if positive
let positiveInteger : Integer = +1

let negativeInteger : Integer = -12

let pi : Double = 3.14159265359

{- You can use a wider character range for identifiers (such as quotation
   marks and whitespace) if you quote them using backticks
-}
let `Avogadro's Number` : Double = 6.0221409e+23

let origin : { x : Double, y : Double } = { x = 0.0, y = 0.0 }

let somePrimes : List Natural = [ 2, 3, 5, 7, 11 ]

{- A schema is the same thing as a type

   Types begin with an uppercase letter by convention, but this convention is
   not enforced
-}
let Profile : Type
        = { person :
              { name : Text
              , age  : Natural
              }
          , address :
              { country : Text
              , state   : Text
              , city    : Text
              }
          }

let john : Profile =
        { person =
            { name = "John Doe"
            , age  = 67
            }
        , address =
            { country = "United States"
            , state   = "Pennsylvania"
            , city    = "Philadelphia"
            }
        }

let philadelphia : Text = john.address.city

{- Enum alternatives also begin with an uppercase letter by convention.  This
   convention is not enforced
-}
let DNA : Type = &lt; Adenine | Cytosine | Guanine | Thymine &gt;

let dnaSequence : List DNA = [ DNA.Thymine, DNA.Guanine, DNA.Guanine ]

let compactDNASequence : List DNA =
        let a = DNA.Adenine
        let c = DNA.Cytosine
        let g = DNA.Guanine
        let t = DNA.Thymine
        in  [ c, t, t, a, t, c, g, g, c ]

-- You can transform enums by providing a record with one field per alternative
let theLetterG : Text =
            merge
            { Adenine  = "A"
            , Cytosine = "C"
            , Guanine  = "G"
            , Thymine  = "T"
            }
            DNA.Guanine

let presentOptionalValue : Optional Natural = Some 1

let absentOptionalValue : Optional Natural = None Natural

let points : List { x : Double, y : Double } =
        [ { x = 1.1, y = -4.2 }
        , { x = 4.4, y = -3.0 }
        , { x = 8.2, y = -5.5 }
        ]

{- `Natural -&gt; List Natural` is the type of a function whose input type is a
   `Natural` and whose output type is a `List Natural`

   All functions in Dhall are anonymous functions (a.k.a. "lambdas"),
   which you can optionally give a name

   For example, the following function is equivalent to this Python code:

       lambda n : [ n, n + 1 ]

   ... and this JavaScript code:

       function (n) { return [ n, n + 1 ]; }
-}
let exampleFunction : Natural -&gt; List Natural =
        \(n : Natural) -&gt; [ n, n + 1 ]

-- Dhall also supports Unicode syntax, but this tutorial will stick to ASCII
let unicodeFunction : Natural → List Natural =
        λ(n : Natural) → [ n, n + 1 ]

-- You don't need to parenthesize function arguments
let exampleFunctionApplication : List Natural =
        exampleFunction 2

let functionOfMultipleArguments : Natural -&gt; Natural -&gt; List Natural =
        \(x : Natural) -&gt; \(y : Natural) -&gt; [ x, y ]

let functionAppliedToMultipleArguments : List Natural =
        functionOfMultipleArguments 2 3

{- Same as `exampleFunction` except we gave the function's input type a
   name: "n"
-}
let namedArgumentType : forall (n : Natural) -&gt; List Natural =
        \(n : Natural) -&gt; [ n, n + 1 ]

{- If you name a function's input type, you can use that name later within the
   same type

   This lets you write a function that works for more than one type of input
   (a.k.a. a "polymorphic" function)
-}
let duplicate : forall (a : Type) -&gt; a -&gt; List a =
        \(a : Type) -&gt; \(x : a) -&gt; [ x, x ] 

let duplicatedNumber : List Natural =
        duplicate Natural 2

let duplicatedBool : List Bool =
        duplicate Bool False

{- The language also has some built-in polymorphic functions, such as:

       List/head : forall (a : Type) -&gt; List a -&gt; Optional a
-}
let firstPrime : Optional Natural = List/head Natural somePrimes

let functionOfARecord : { x : Natural, y : Natural } -&gt; List Natural =
        \(args : { x : Natural, y : Natural }) -&gt; [ args.x, args.y ]

let functionAppliedToARecord : List Natural =
        functionOfARecord { x = 2, y = 5 }

{- All type conversions are explicit

   `Natural/show` is a built-in function of the following type:

       Natural/show : Natural -&gt; Text

   ... that converts `Natural` numbers to their `Text` representation
-}
let typeConversion : Natural -&gt; Text =
        \(age : Natural) -&gt; "I am ${Natural/show age} years old!"

-- A "template" is the same thing as a function whose output type is `Text`
let mitLicense : { year : Natural, copyrightHolder : Text } -&gt; Text =
        \(args : { year : Natural, copyrightHolder : Text }) -&gt;
''
Copyright ${Natural/show args.year} ${args.copyrightHolder}

Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal in 
the Software without restriction, including without limitation the rights to 
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
of the Software, and to permit persons to whom the Software is furnished to do 
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
SOFTWARE.
''

-- Template instantiation is the same thing as function application
let templatedLicense : Text =
        mitLicense { year = 2019, copyrightHolder = "Jane Smith" }

{- You can import expressions by URL

   Also, like Bash, you can import code from your local filesystem (not shown)

   Security-conscious users can pin remotely-imported expressions by adding a
   semantic integrity check.  The interpreter rejects any attempt to tamper with
   an expression pinned in this way.  However, behavior-preserving refactors
   of imported content will not perturb the hash.

   Imported expressions pinned in this way are also locally cached in a
   content-addressable store (typically underneath `~/.cache/dhall`)
-}
let Natural/sum : List Natural -&gt; Natural =
      https://prelude.dhall-lang.org/Natural/sum
      sha256:33f7f4c3aff62e5ecf4848f964363133452d420dcde045784518fb59fa970037

let twentyEight : Natural = Natural/sum somePrimes

-- A "package" is the same thing as a (possibly nested) record that you can import
let Prelude = https://prelude.dhall-lang.org/package.dhall

let false : Bool = Prelude.Bool.not True

-- You can import the raw contents of a file by adding `as Text` to an import
let sourceCode : Text = https://prelude.dhall-lang.org/Bool/not as Text

-- You can import environment variables, too:
let presentWorkingDirectory = env:PWD as Text

-- You can provide a fallback expression if an import fails
let home : Optional Text = Some env:HOME ? None Text

-- Fallback expressions can contain alternative imports of their own
let possiblyCustomPrelude =
        env:DHALL_PRELUDE
      ? https://prelude.dhall-lang.org/package.dhall

{- Tie everything together by auto-generating configurations for 10 build users
   using the `generate` function:

       Prelude.List.generate
           : Natural -&gt; forall (a : Type) -&gt; (Natural -&gt; a) -&gt; List a
-}
let buildUsers =
        let makeUser = \(user : Text) -&gt;
              let home       = "/home/${user}"
              let privateKey = "${home}/.ssh/id_ed25519"
              let publicKey  = "${privateKey}.pub"
              in  { home = home
                  , privateKey = privateKey
                  , publicKey = publicKey
                  }

        let buildUser =
                \(index : Natural) -&gt; makeUser "build${Natural/show index}"

        let Config =
              { home : Text
              , privateKey : Text
              , publicKey : Text
              }

        in  Prelude.List.generate 10 Config buildUser

-- Present all of the results in a final record
in  { greeting = greeting
    , fruits = fruits
    , interpolation = interpolation
    , multilineText = multilineText
    , bool = bool
    , annotation = annotation
    , renderedBool = renderedBool
    , naturalNumber = naturalNumber
    , positiveInteger = positiveInteger
    , negativeInteger = negativeInteger
    , pi = pi
    , `Avogadro's Number` = `Avogadro's Number`
    , origin = origin
    , somePrimes = somePrimes
    , john = john
    , philadelphia = philadelphia
    , dnaSequence = dnaSequence
    , compactDNASequence = compactDNASequence
    , theLetterG = theLetterG
    , presentOptionalValue = presentOptionalValue
    , absentOptionalValue = absentOptionalValue
    , points = points
    , exampleFunction = exampleFunction
    , unicodeFunction = unicodeFunction
    , exampleFunctionApplication = exampleFunctionApplication
    , functionOfMultipleArguments = functionOfMultipleArguments
    , functionAppliedToMultipleArguments = functionAppliedToMultipleArguments
    , namedArgumentType = namedArgumentType
    , duplicate = duplicate
    , duplicatedNumber = duplicatedNumber
    , duplicatedBool = duplicatedBool
    , firstPrime = firstPrime
    , functionOfARecord = functionOfARecord
    , functionAppliedToARecord = functionAppliedToARecord
    , typeConversion = typeConversion
    , mitLicense = mitLicense
    , templatedLicense = templatedLicense
    , twentyEight = twentyEight
    , false = false
    , sourceCode = sourceCode
    , presentWorkingDirectory = presentWorkingDirectory
    , home = home
    , buildUsers = buildUsers
    }
</code></pre>
<p>EasyLang:</p>
<pre><code class="lang-plaintext">print "Hello world"
#
# number variable (64 bit floating point)
#
h = 3.14
print h
#
# string variable
#
str$ = "monkey"
# strings can grow
str$ &amp;= " circus" 
print str$
#
# blocks end with 'end' or a dot, a newline has no
# other meaning than a space
#
for i = 1 to 5
  sum += i * i
.
print sum
#
# functions have value and reference
# parameters, no return values
#
func gcd a b . res .
  # a and b are value parameters
  # res is a reference parameter
  while b &lt;&gt; 0
    # h is a local variable, because 
    # it is first used in the function
    h = b
    b = a mod b
    a = h
  .
  res = a
.
call gcd 120 35 r
print r
#
# strings can be concatenated and numbers are
# automatically converted to strings
#
print "1 + 2 = " &amp; 1 + 2
#
# array of numbers
#
a[] = [ 2.1 3.14 3 ]
#
# arrays can grow
a[] &amp;= 4
print a[]
#
# arrays, strings and numbers are copied by value
#
b[] = a[]
a[] &amp;= 4
print a[] ; print b[]
#
# array swapping ist fast
#
swap a[] b[]
print a[] ; print b[]
# 
# array of strings
#
fruits$[] = [ "apple" "banana" "orange" ]
#
# for-in iterates over the elements of an array
#
for fruit$ in fruits$[]
  print fruit$
.
#
# strings are also used for single characters
#
letters$[] = str_chars "ping"
print letters$[]
letters$[1] = "o"
print str_join letters$[]
#
# 2-dimensional arrays are arrays of arrays
# this defines 3 arrays with length 4
#
len a[][] 3
for i range len a[][]
  len a[i][] 4
.
a[1][2] = 99
print a[][]
#
# builtin functions
if sin 90 = 1
  print "angles are in degree"
.
print pow 2 8
# seconds since 1970
print floor sys_time
# random numbers
print randomf
print random 6 + 1
# 
# hour and minutes
print substr time_str sys_time 11 5
# 
print str_ord "A"
print str_chr 65
# 
# set number format
numfmt 0 4
print sqrt 2
print pi
print logn 10
# 
a$[] = str_split "10,15,22" ","
print a$[]
print 2 * number a$[0]
print len a$[]
print len "Hello"
#
# With 'break n' you can leave nested loops and a function
#
names$[] = [ ]
func name2id name$ . id .
  for id range len names$[]
    if names$[id] = name$
      # leave loop and function
      break 2
    .
  .
  names$[] &amp;= name$
.
call name2id "alice" id ; print id
call name2id "bob" id ; print id
call name2id "alice" id ; print i
#
# with 'repeat' you can make loops, which you can leave
# in the loop body using 'until'
#
sum = 0
repeat
  s$ = input
  until s$ = ""
  sum += number s$
.
print "sum: " &amp; sum
#
# "input" reads a string from the "input_data" section, 
# if it exists, otherwise via a prompt.
#
input_data
10
-2
6
</code></pre>
<p>EDN:</p>
<pre><code class="lang-plaintext">; Comments start with a semicolon.
; Anything after the semicolon is ignored.

;;;;;;;;;;;;;;;;;;;
;;; Basic Types ;;;
;;;;;;;;;;;;;;;;;;;

nil         ; also known in other languages as null

; Booleans
true
false

; Strings are enclosed in double quotes
"hungarian breakfast"
"farmer's cheesy omelette"

; Characters are preceded by backslashes
\g \r \a \c \e

; Keywords start with a colon. They behave like enums. Kind of
; like symbols in Ruby.
:eggs
:cheese
:olives

; Symbols are used to represent identifiers. 
; You can namespace symbols by using /. Whatever precedes / is
; the namespace of the symbol.
spoon
kitchen/spoon ; not the same as spoon
kitchen/fork
github/fork   ; you can't eat with this

; Integers and floats
42
3.14159

; Lists are sequences of values
(:bun :beef-patty 9 "yum!")

; Vectors allow random access
[:gelato 1 2 -2]

; Maps are associative data structures that associate the key with its value
{:eggs        2
 :lemon-juice 3.5
 :butter      1}

; You're not restricted to using keywords as keys
{[1 2 3 4] "tell the people what she wore",
 [5 6 7 8] "the more you see the more you hate"}

; You may use commas for readability. They are treated as whitespace.

; Sets are collections that contain unique elements.
#{:a :b 88 "huat"}

;;;;;;;;;;;;;;;;;;;;;;;
;;; Tagged Elements ;;;
;;;;;;;;;;;;;;;;;;;;;;;

; EDN can be extended by tagging elements with # symbols.

#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10}

; Let me explain this with a Clojure example. Suppose I want to transform that
; piece of EDN into a MenuItem record.

(defrecord MenuItem [name rating])

; defrecord defined, among other things, map-&gt;MenuItem which will take a map
; of field names (as keywords) to values and generate a user.MenuItem record

; To transform EDN to Clojure values, I will need to use the built-in EDN
; reader, clojure.edn/read-string

(clojure.edn/read-string "{:eggs 2 :butter 1 :flour 5}")
; -&gt; {:eggs 2 :butter 1 :flour 5}

; To transform tagged elements, pass to clojure.edn/read-string an option map
; with a :readers map that maps tag symbols to data-reader functions, like so

(clojure.edn/read-string
    {:readers {'MyYelpClone/MenuItem map-&gt;MenuItem}}
    "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}")
; -&gt; #user.MenuItem{:name "eggs-benedict", :rating 10}
</code></pre>
<p>Elixir:</p>
<pre><code class="lang-plaintext"># Single line comments start with a number symbol.

# There's no multi-line comment,
# but you can stack multiple comments.

# To use the Elixir shell use the `iex` command.
# Compile your modules with the `elixirc` command.

# Both should be in your path if you installed Elixir correctly.

## ---------------------------
## -- Basic types
## ---------------------------

# There are numbers
3    # integer
0x1F # integer
3.0  # float

# Atoms are constants whose values are their own name. They start with `:`.
:hello # atom

# Tuples that are stored contiguously in memory.
{1,2,3} # tuple

# We can access a tuple element with the `elem` function:
elem({1, 2, 3}, 0) #=&gt; 1

# Lists that are implemented as linked lists.
[1,2,3] # list

# We can access the head and tail of a list as follows:
[head | tail] = [1,2,3]
head #=&gt; 1
tail #=&gt; [2,3]

# In Elixir, just like in Erlang, the `=` denotes pattern matching and
# not an assignment.
#
# This means that the left-hand side (pattern) is matched against a
# right-hand side.
#
# This is how the above example of accessing the head and tail of a list works.

# A pattern match will error when the sides don't match, in this example
# the tuples have different sizes.
# {a, b, c} = {1, 2} #=&gt; ** (MatchError) no match of right hand side value: {1,2}

# There are also binaries
&lt;&lt;1,2,3&gt;&gt; # binary

# Strings and char lists
"hello" # string
'hello' # char list

# Multi-line strings
"""
I'm a multi-line
string.
"""
#=&gt; "I'm a multi-line\nstring.\n"

# Strings are all encoded in UTF-8:
"héllò" #=&gt; "héllò"

# Strings are really just binaries, and char lists are just lists.
&lt;&lt;?a, ?b, ?c&gt;&gt; #=&gt; "abc"
[?a, ?b, ?c]   #=&gt; 'abc'

# `?a` in Elixir returns the ASCII integer for the letter `a`
?a #=&gt; 97

# To concatenate lists use `++`, for binaries use `&lt;&gt;`
[1,2,3] ++ [4,5]     #=&gt; [1,2,3,4,5]
'hello ' ++ 'world'  #=&gt; 'hello world'

&lt;&lt;1,2,3&gt;&gt; &lt;&gt; &lt;&lt;4,5&gt;&gt; #=&gt; &lt;&lt;1,2,3,4,5&gt;&gt;
"hello " &lt;&gt; "world"  #=&gt; "hello world"

# Ranges are represented as `start..end` (both inclusive)
1..10 #=&gt; 1..10
lower..upper = 1..10 # Can use pattern matching on ranges as well
[lower, upper] #=&gt; [1, 10]

# Maps are key-value pairs
genders = %{"david" =&gt; "male", "gillian" =&gt; "female"}
genders["david"] #=&gt; "male"

# Maps with atom keys can be used like this
genders = %{david: "male", gillian: "female"}
genders.gillian #=&gt; "female"

## ---------------------------
## -- Operators
## ---------------------------

# Some math
1 + 1  #=&gt; 2
10 - 5 #=&gt; 5
5 * 2  #=&gt; 10
10 / 2 #=&gt; 5.0

# In Elixir the operator `/` always returns a float.

# To do integer division use `div`
div(10, 2) #=&gt; 5

# To get the division remainder use `rem`
rem(10, 3) #=&gt; 1

# There are also boolean operators: `or`, `and` and `not`.
# These operators expect a boolean as their first argument.
true and true #=&gt; true
false or true #=&gt; true
# 1 and true
#=&gt; ** (BadBooleanError) expected a boolean on left-side of "and", got: 1

# Elixir also provides `||`, `&amp;&amp;` and `!` which accept arguments of any type.
# All values except `false` and `nil` will evaluate to true.
1 || true  #=&gt; 1
false &amp;&amp; 1 #=&gt; false
nil &amp;&amp; 20  #=&gt; nil
!true #=&gt; false

# For comparisons we have: `==`, `!=`, `===`, `!==`, `&lt;=`, `&gt;=`, `&lt;` and `&gt;`
1 == 1 #=&gt; true
1 != 1 #=&gt; false
1 &lt; 2  #=&gt; true

# `===` and `!==` are more strict when comparing integers and floats:
1 == 1.0  #=&gt; true
1 === 1.0 #=&gt; false

# Elixir operators are strict in their arguments, with the exception
# of comparison operators that work across different data types:
1 &lt; :hello #=&gt; true

# This enables building collections of mixed types:
["string", 123, :atom]

# While there is an overall order of all data types,
# to quote Joe Armstrong on this: "The actual order is not important,
# but that a total ordering is well defined is important."

## ---------------------------
## -- Control Flow
## ---------------------------

# `if` expression
if false do
  "This will never be seen"
else
  "This will"
end

# There's also `unless`
unless true do
  "This will never be seen"
else
  "This will"
end

# Remember pattern matching? Many control-flow structures in Elixir rely on it.

# `case` allows us to compare a value against many patterns:
case {:one, :two} do
  {:four, :five} -&gt;
    "This won't match"
  {:one, x} -&gt;
    "This will match and bind `x` to `:two` in this clause"
  _ -&gt;
    "This will match any value"
end

# It's common to bind the value to `_` if we don't need it.
# For example, if only the head of a list matters to us:
[head | _] = [1,2,3]
head #=&gt; 1

# For better readability we can do the following:
[head | _tail] = [:a, :b, :c]
head #=&gt; :a

# `cond` lets us check for many conditions at the same time.
# Use `cond` instead of nesting many `if` expressions.
cond do
  1 + 1 == 3 -&gt;
    "I will never be seen"
  2 * 5 == 12 -&gt;
    "Me neither"
  1 + 2 == 3 -&gt;
    "But I will"
end

# It is common to set the last condition equal to `true`, which will always match.
cond do
  1 + 1 == 3 -&gt;
    "I will never be seen"
  2 * 5 == 12 -&gt;
    "Me neither"
  true -&gt;
    "But I will (this is essentially an else)"
end

# `try/catch` is used to catch values that are thrown, it also supports an
# `after` clause that is invoked whether or not a value is caught.
try do
  throw(:hello)
catch
  message -&gt; "Got #{message}."
after
  IO.puts("I'm the after clause.")
end
#=&gt; I'm the after clause
# "Got :hello"

## ---------------------------
## -- Modules and Functions
## ---------------------------

# Anonymous functions (notice the dot)
square = fn(x) -&gt; x * x end
square.(5) #=&gt; 25

# They also accept many clauses and guards.
# Guards let you fine tune pattern matching,
# they are indicated by the `when` keyword:
f = fn
  x, y when x &gt; 0 -&gt; x + y
  x, y -&gt; x * y
end

f.(1, 3)  #=&gt; 4
f.(-1, 3) #=&gt; -3

# Elixir also provides many built-in functions.
# These are available in the current scope.
is_number(10)    #=&gt; true
is_list("hello") #=&gt; false
elem({1,2,3}, 0) #=&gt; 1

# You can group several functions into a module. Inside a module use `def`
# to define your functions.
defmodule Math do
  def sum(a, b) do
    a + b
  end

  def square(x) do
    x * x
  end
end

Math.sum(1, 2)  #=&gt; 3
Math.square(3) #=&gt; 9

# To compile our simple Math module save it as `math.ex` and use `elixirc`
# in your terminal: elixirc math.ex

# Inside a module we can define functions with `def` and private functions with `defp`.
# A function defined with `def` is available to be invoked from other modules,
# a private function can only be invoked locally.
defmodule PrivateMath do
  def sum(a, b) do
    do_sum(a, b)
  end

  defp do_sum(a, b) do
    a + b
  end
end

PrivateMath.sum(1, 2)    #=&gt; 3
# PrivateMath.do_sum(1, 2) #=&gt; ** (UndefinedFunctionError)

# Function declarations also support guards and multiple clauses.
# When a function with multiple clauses is called, the first function
# that satisfies the clause will be invoked.
# Example: invoking area({:circle, 3}) will call the second area
# function defined below, not the first:
defmodule Geometry do
  def area({:rectangle, w, h}) do
    w * h
  end

  def area({:circle, r}) when is_number(r) do
    3.14 * r * r
  end
end

Geometry.area({:rectangle, 2, 3}) #=&gt; 6
Geometry.area({:circle, 3})       #=&gt; 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=&gt; ** (FunctionClauseError) no function clause matching in Geometry.area/1

# Due to immutability, recursion is a big part of Elixir
defmodule Recursion do
  def sum_list([head | tail], acc) do
    sum_list(tail, acc + head)
  end

  def sum_list([], acc) do
    acc
  end
end

Recursion.sum_list([1,2,3], 0) #=&gt; 6

# Elixir modules support attributes, there are built-in attributes and you
# may also add custom ones.
defmodule MyMod do
  @moduledoc """
  This is a built-in attribute on an example module.
  """

  @my_data 100 # This is a custom attribute.
  IO.inspect(@my_data) #=&gt; 100
end

# The pipe operator |&gt; allows you to pass the output of an expression
# as the first parameter into a function. 

Range.new(1,10)
|&gt; Enum.map(fn x -&gt; x * x end)
|&gt; Enum.filter(fn x -&gt; rem(x, 2) == 0 end)
#=&gt; [4, 16, 36, 64, 100]

## ---------------------------
## -- Structs and Exceptions
## ---------------------------

# Structs are extensions on top of maps that bring default values,
# compile-time guarantees and polymorphism into Elixir.
defmodule Person do
  defstruct name: nil, age: 0, height: 0
end

joe_info = %Person{ name: "Joe", age: 30, height: 180 }
#=&gt; %Person{age: 30, height: 180, name: "Joe"}

# Access the value of name
joe_info.name #=&gt; "Joe"

# Update the value of age
older_joe_info = %{ joe_info | age: 31 }
#=&gt; %Person{age: 31, height: 180, name: "Joe"}

# The `try` block with the `rescue` keyword is used to handle exceptions
try do
  raise "some error"
rescue
  RuntimeError -&gt; "rescued a runtime error"
  _error -&gt; "this will rescue any error"
end
#=&gt; "rescued a runtime error"

# All exceptions have a message
try do
  raise "some error"
rescue
  x in [RuntimeError] -&gt;
    x.message
end
#=&gt; "some error"

## ---------------------------
## -- Concurrency
## ---------------------------

# Elixir relies on the actor model for concurrency. All we need to write
# concurrent programs in Elixir are three primitives: spawning processes,
# sending messages and receiving messages.

# To start a new process we use the `spawn` function, which takes a function
# as argument.
f = fn -&gt; 2 * 2 end #=&gt; #Function&lt;erl_eval.20.80484245&gt;
spawn(f) #=&gt; #PID&lt;0.40.0&gt;

# `spawn` returns a pid (process identifier), you can use this pid to send
# messages to the process. To do message passing we use the `send` operator.
# For all of this to be useful we need to be able to receive messages. This is
# achieved with the `receive` mechanism:

# The `receive do` block is used to listen for messages and process
# them when they are received. A `receive do` block will only
# process one received message. In order to process multiple
# messages, a function with a `receive do` block must recursively
# call itself to get into the `receive do` block again.

defmodule Geometry do
  def area_loop do
    receive do
      {:rectangle, w, h} -&gt;
        IO.puts("Area = #{w * h}")
        area_loop()
      {:circle, r} -&gt;
        IO.puts("Area = #{3.14 * r * r}")
        area_loop()
    end
  end
end

# Compile the module and create a process that evaluates `area_loop` in the shell
pid = spawn(fn -&gt; Geometry.area_loop() end) #=&gt; #PID&lt;0.40.0&gt;
# Alternatively
pid = spawn(Geometry, :area_loop, [])

# Send a message to `pid` that will match a pattern in the receive statement
send pid, {:rectangle, 2, 3}
#=&gt; Area = 6
#   {:rectangle,2,3}

send pid, {:circle, 2}
#=&gt; Area = 12.56000000000000049738
#   {:circle,2}

# The shell is also a process, you can use `self` to get the current pid
self() #=&gt; #PID&lt;0.27.0&gt;

## ---------------------------
## -- Agents
## ---------------------------

# An agent is a process that keeps track of some changing value

# Create an agent with `Agent.start_link`, passing in a function
# The initial state of the agent will be whatever that function returns
{:ok, my_agent} = Agent.start_link(fn -&gt; ["red", "green"] end)

# `Agent.get` takes an agent name and a `fn` that gets passed the current state
# Whatever that `fn` returns is what you'll get back
Agent.get(my_agent, fn colors -&gt; colors end) #=&gt; ["red", "green"]

# Update the agent's state the same way
Agent.update(my_agent, fn colors -&gt; ["blue" | colors] end)
</code></pre>
<p>Stop updates.</p>
]]></content:encoded></item><item><title><![CDATA[Aq 字节码结构调整]]></title><description><![CDATA[为了适应自定义类型的需求，对于虚拟机应有相应改变以便于发挥动态语言的独有优势和更高效率（相较于未在字节码支持自定义类型）。更改内容：Add new features about class in vm. · Issue #247 · aq-org/AQ。但是对于相关字节码的结构尚未存在明确的记录，仅在代码中存有部分记录。为完善详细的字节码结构，该文章具体指出了字节码的结构以及其对应变化。
原字节码结构：

魔数：AQBC(0x41 0×51 0×42 0x43) 4字节

版本号：32位正整数 ...]]></description><link>https://blog.axa6.com/aq-1</link><guid isPermaLink="true">https://blog.axa6.com/aq-1</guid><category><![CDATA[bytecode]]></category><category><![CDATA[virtual machine]]></category><category><![CDATA[compiler]]></category><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Tue, 04 Mar 2025 14:08:28 GMT</pubDate><content:encoded><![CDATA[<p>为了适应自定义类型的需求，对于虚拟机应有相应改变以便于发挥动态语言的独有优势和更高效率（相较于未在字节码支持自定义类型）。更改内容：<a target="_blank" href="https://github.com/aq-org/AQ/issues/247">Add new features about class in vm. · Issue #247 · aq-org/AQ</a>。但是对于相关字节码的结构尚未存在明确的记录，仅在代码中存有部分记录。为完善详细的字节码结构，该文章具体指出了字节码的结构以及其对应变化。</p>
<p>原字节码结构：</p>
<ol>
<li><p>魔数：AQBC(0x41 0×51 0×42 0x43) 4字节</p>
</li>
<li><p>版本号：32位正整数 4字节</p>
</li>
<li><p>常量池</p>
<ol>
<li><p>常量池长度：64位正整数 8字节</p>
</li>
<li><p>常量池内容：1字节用于类型，后面根据类型定义结束（Byte：1字节，Long、Double、Uint64t、指针：8字节，String：根据’\0’出现的位置决定结束）</p>
</li>
</ol>
</li>
<li><p>变量类型表</p>
<ol>
<li><p>变量类型表长度：64位正整数 8字节</p>
</li>
<li><p>变量类型表内容：正常类型（动态类型（0×00）、Byte、Long、Double、Uint64_t）1字节，特殊类型（指针，引用，const）1字节后附带类型直到遇到正常类型（包含动态类型（0×00）），Class类型检测后一个数据（Uleb128算法的常量表索引（作为其名称））</p>
</li>
</ol>
</li>
<li><p>Class</p>
<ol>
<li><p>Class名称：根据’\0’出现的位置决定结束</p>
</li>
<li><p>Class内变量类型表：</p>
<ol>
<li><p>变量类型表长度：64位正整数 8字节</p>
</li>
<li><p>变量类型表内容：正常类型（动态类型（0×00）、Byte、Long、Double、Uint64_t）1字节，特殊类型（指针，引用，const）1字节后附带类型直到遇到正常类型（包含动态类型（0×00）），Class类型检测后一个数据（Uleb128算法的常量表索引（作为其名称））</p>
</li>
</ol>
</li>
<li><p>函数表</p>
<ol>
<li><p>函数数量：64位正整数 8字节</p>
</li>
<li><p>函数名称：根据’\0’出现的位置决定结束</p>
</li>
<li><p>函数参数</p>
<ol>
<li><p>函数参数数量：Uleb128算法的正整数</p>
</li>
<li><p>函数参数内容：正常类型（动态类型（0×00）、Byte、Long、Double、Uint64_t）1字节，特殊类型（指针，引用，const）1字节后附带类型直到遇到正常类型（包含动态类型（0×00））</p>
</li>
</ol>
</li>
<li><p>函数体</p>
<ol>
<li><p>函数体长度：64位正整数 8字节</p>
</li>
<li><p>函数体内容：1字节的操作数（WIDE操作符可能多字节（目前未启用））附带相关操作数（数量根据操作符的参数决定）。</p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
<p>仍需对应的函数支持。</p>
]]></content:encoded></item><item><title><![CDATA[Architecture adjustment of Aq virtual machine and bytecode]]></title><description><![CDATA[Yesterday, AQ v0.1.0-alpha was released, and the virtual machine design continued the previous architecture without any architecture level adjustments. For current needs, it can meet certain requirements. However, in the recent development process, a...]]></description><link>https://blog.axa6.com/architecture-adjustment-of-aq-virtual-machine-and-bytecode</link><guid isPermaLink="true">https://blog.axa6.com/architecture-adjustment-of-aq-virtual-machine-and-bytecode</guid><category><![CDATA[AQ]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[virtual machine]]></category><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Sun, 02 Feb 2025 06:27:58 GMT</pubDate><content:encoded><![CDATA[<p>Yesterday, AQ v0.1.0-alpha was released, and the virtual machine design continued the previous architecture without any architecture level adjustments. For current needs, it can meet certain requirements. However, in the recent development process, areas that can be optimized have been identified. The focus is on adjusting the memory architecture.</p>
<p>At present, bytecode directly stores all memory data and types. A large amount of data among them needs to be written by the virtual machine during runtime, so a large amount of data is allocated when not in use, resulting in a lot of memory waste. For the example Hello World (hello world. aq, hello world. aqbc), the AQ v0.1.0-alpha source code only occupies about 50 bytes, but the bytecode memory occupies about 100 bytes. To some extent, the original purpose of bytecode - to save memory - has failed to play a role and has increased the burden.</p>
<p>Therefore, it is extremely necessary to adjust the architecture of AQ virtual machines and bytecode. Refer to current interpreted programming languages. The most common approach is to use a constant pool.</p>
<p>To achieve this goal, the following changes are required:</p>
<ol>
<li><p>Modify the relevant code of the compiler.</p>
</li>
<li><p>Modify the relevant code of the virtual machine.</p>
</li>
<li><p>Add new instructions to read data from the constant pool.</p>
</li>
<li><p>Adjust the original type storage method and refer to the bytecode constant pool design methods in Python and JavaScript.</p>
</li>
</ol>
<p>There is still a significant amount of resource waste at present, and this issue should be addressed when AQ v0.11-alpha is released.</p>
<p>Meanwhile, in addition to the issues mentioned here, there are still many unresolved issues in the release of AQ v0.1.0-alpha. One of the more serious issues is the failure to handle the parameters and return values of custom functions.</p>
<p>For this issue, one should also refer to the design ideas of interpreted programming languages such as Python and JavaScript. Optimize function calls to avoid wasting resources during the calling process.</p>
<p>In addition, there is an extremely important issue that has not been resolved in this version release - the design of implementing standard libraries and the calling of third-party libraries. At present, only print function is supported, and third-party libraries cannot call it. Therefore, the resolution should also be accelerated.</p>
<p>In this version, there are still type conversion errors that cannot be automatically converted and should be fixed as soon as possible.</p>
<p>In this version, support for new syntax is still lacking and should be added as soon as possible.</p>
<p>In this version, support for dynamic types is not available and should be added in subsequent compiler and virtual machine adjustments.</p>
<p>Finally, the release of AQ v0.1.1-alpha version will also follow closely, and relevant issues should be resolved as soon as possible.</p>
]]></content:encoded></item><item><title><![CDATA[Aq 虚拟机及字节码的架构调整]]></title><description><![CDATA[昨天发布了 AQ v0.1.0-alpha ，其中的虚拟机设计延续了以往的架构，未做架构级别的调整。对于目前的需求来说，可以满足一定的要求。但是在近日的开发过程中，发现了可以进行优化的地方。其中重点为内存架构的调整。
现阶段的字节码直接存储所有的内存数据和类型。其中大量的额数据都是需要虚拟机在运行时决定的数据写入，因此大量的数据在未使用时被分配，造成了大量的内存浪费。对于示例 Hello World (hello-world.aq, hello-world.aqbc) 来说，AQ v0.1.0-...]]></description><link>https://blog.axa6.com/aq</link><guid isPermaLink="true">https://blog.axa6.com/aq</guid><category><![CDATA[AQ]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[virtual machine]]></category><category><![CDATA[bytecode]]></category><dc:creator><![CDATA[Xie Zicong]]></dc:creator><pubDate>Sun, 02 Feb 2025 06:25:22 GMT</pubDate><content:encoded><![CDATA[<p>昨天发布了 AQ v0.1.0-alpha ，其中的虚拟机设计延续了以往的架构，未做架构级别的调整。对于目前的需求来说，可以满足一定的要求。但是在近日的开发过程中，发现了可以进行优化的地方。其中重点为内存架构的调整。</p>
<p>现阶段的字节码直接存储所有的内存数据和类型。其中大量的额数据都是需要虚拟机在运行时决定的数据写入，因此大量的数据在未使用时被分配，造成了大量的内存浪费。对于示例 Hello World (hello-world.aq, hello-world.aqbc) 来说，AQ v0.1.0-alpha 源代码仅有50字节左右的占用，但是在字节码的内存占用却有100字节左右的占用。从一定程度上说，字节码原先的作用——节省内存已经未能发挥作用，并且加重了负担。</p>
<p>因此对于AQ虚拟机和字节码的架构调整极其必要。参照现阶段的解释性编程语言。使用常量池是最为常见的思路。</p>
<p>为完成该目标，需要以下的改变：</p>
<ol>
<li><p>修改编译器的相关代码。</p>
</li>
<li><p>修改虚拟机的相关代码。</p>
</li>
<li><p>增加新的指令，实现从常量池读取数据。</p>
</li>
<li><p>将原先的类型存储方法进行调整，参照 Python、JavaScript 的字节码常量池设计方法。</p>
</li>
</ol>
<p>目前仍有大量的资源浪费，在 AQ v0.1.1-alpha 发布时应解决此问题。</p>
<p>同时，除此处的问题，AQ v0.1.0-alpha 的发布中仍有不少的问题未能解决。其中较为严重的就是：未能实现自定义函数的参数和返回值的处理。</p>
<p>对于该问题，同样应参见Python、JavaScript等解释性编程语言的设计思路。对于函数调用进行优化，避免存在调用过程中的资源浪费。</p>
<p>除此之外，此次版本发布还有一个极其重要的问题未能解决——实现标准库的设计和第三方库的调用。目前仅支持print一个函数，同时第三方库无法调用。因此同样应加快解决。</p>
<p>该版本中，仍存在类型转换的错误，无法自动进行类型转换，应尽快修复。</p>
<p>该版本中，对于新的语法支持仍然欠缺，应尽快添加支持。</p>
<p>该版本中，对于动态类型未能支持，应当在后续的编译器和虚拟机的调整中加入支持。</p>
<p>最后，AQ v0.1.1-alpha 版本的发布也将紧随其后，应当尽快解决相关问题。</p>
]]></content:encoded></item></channel></rss>