From 293916c8f4dc109082ecd709e5e4c19a0847b0cd Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Fri, 9 Feb 2024 21:02:57 +0100 Subject: wip --- step-03/README.md | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 step-03/README.md (limited to 'step-03/README.md') diff --git a/step-03/README.md b/step-03/README.md new file mode 100644 index 0000000..cd2fd9b --- /dev/null +++ b/step-03/README.md @@ -0,0 +1,98 @@ +# More syntax + +A function is identified by its name (`foo`) and the number of arguments it has. A function can be declared multiple times while pattern matching on it's arguments: + +``` +fac(1) -> + 1; +fac(N) -> + N * fac(N - 1). +``` + +Notice the semi-colon between the declarations. + +Try out [tut1](./tut1.erl): + +``` +1> c(tut1). +{ok,tut1} +2> tut1:fac(1). +1 +3> tut1:fac(10). +3628800 +``` + +# Atoms + +An atom is data type that starts with a lower-case letter. In the previous examples `ok` and `tut1` are atoms. They are kinda like unmodifyable strings, but are used as identifiers. + +[tut2](./tut2.erl) is another example of overloading, but with atoms: + +``` +1> c(tut2). +{ok,tut2} +2> tut2:convert(23, centimeter). +58.42 +``` + +# More pattern matching + +Tuples are dentonated as: `{a, b, c}`. They can be used when pattern matching as seen in [tut3](./tut3.erl). + +``` +1> c(tut3). +{ok,tut3} +2> tut3:convert_length({inch, 23}). +{centimeter,58.42} +``` + +# Lists + +Lists are dentonated as: `[a, b, c]`, for example: + +```erlang +Temps = [ + {moscow, {c, -10}}, + {cape_town, {f, 70}}, + {stockholm, {c, -4}}, + {paris, {f, 28}}, + {london, {f, 36}} +]. +``` + +Lists are, as they commonly are in functional languages, linked lists and it is common to work on the head of the list: + +``` +1> [First | Rest] = Temps. +[{moscow,{c,-10}}, + {cape_town,{f,70}}, + {stockholm,{c,-4}}, + {paris,{f,28}}, + {london,{f,36}}] +2> First. +{moscow,{c,-10}} +3> Rest. +[{cape_town,{f,70}}, + {stockholm,{c,-4}}, + {paris,{f,28}}, + {london,{f,36}}] +``` + +``` +1> [First, Second | Rest] = Temps. +[{moscow,{c,-10}}, + {cape_town,{f,70}}, + {stockholm,{c,-4}}, + {paris,{f,28}}, + {london,{f,36}}] +2> First. +{moscow,{c,-10}} +3> Second. +{cape_town,{f,70}} +4> Rest. +[{stockholm,{c,-4}},{paris,{f,28}},{london,{f,36}}] +``` + +# Maps + +Maps are dentonated as `#{foo => bar}` -- cgit v1.2.3