Functional Programming Snippets in JavaScript and Julia

A comparison of small code snippets to show some of the advantages of Julia for functional programming

Computing the Sum of a List of Elements

> xs = [2, 4, 8]
[ 2, 4, 8 ]
> xs.reduce((total, x) => total + x)
14
julia> xs = [2, 4, 8]
3-element Vector{Int64}:
2
4
8
julia> sum(xs)
14
julia> reduce((total, x) -> total + x, xs)
14
julia> 3 + 4
7
julia> +(3, 4)
7
julia> reduce(+, xs)
14
julia> factorial(4)
24
julia> reduce(*, 1:4)
24

Gathering Values of a Dictionary

> nums = [{number: "two"}, {number: "four"}]

> nums.map(item => item.number).join(" ")
'two four'
julia> nums = ["number" => "two", "number" => "four"]julia> join(map(last, nums), " ")
"two four five"
julia> pair = "number" => "two"
"number" => "two"
julia> first(pair)
"number"
julia> last(pair)
"two"
julia> range = 4:8
4:8
julia> first(range)
4
julia> last(range)
8
julia> map(range -> first(range), [2:8, 4:8, 5:6])
3-element Vector{Int64}:
2
4
5
julia> map(first, [2:8, 4:8, 5:6])
3-element Vector{Int64}:
2
4
5
julia> map(last, [2:8, 4:8, 5:6])
3-element Vector{Int64}:
8
8
6

Getting the Unicode Codepoints of Characters in String

> [..."Þrúðvangr"].map(ch => ch.codePointAt())
[
222, 114, 250, 240,
118, 97, 110, 103,
114
]
julia> map(codepoint, ["Þrúðvangr"...])
9-element Vector{UInt32}:
0x000000de
0x00000072
0x000000fa
0x000000f0
0x00000076
0x00000061
0x0000006e
0x00000067
0x00000072
map(codepoint, collect("Þrúðvangr"))
broadcast(codepoint, collect("Þrúðvangr"))
codepoint.(collect("Þrúðvangr"))
julia> broadcast(+, [3, 4], [2, 5])
2-element Vector{Int64}:
5
9
julia> broadcast(+, [3, 4], 10)
2-element Vector{Int64}:
13
14

Creating a Dictionary From Array

> chars = ['a', 'b', 'c']
[ 'a', 'b', 'c' ]
> chars.reduce((dict, ch, i) => {
dict[ch] = i;
return dict
}, {});
{ a: 0, b: 1, c: 2 }
> dict = {}
{}
> chars.forEach((ch, i) => dict[ch] = i)
undefined
> dict
{ a: 0, b: 1, c: 2 }
julia> Dict(ch => i for (i, ch) in enumerate(chars))
Dict{Char, Int64} with 3 entries:
'a' => 1
'c' => 3
'b' => 2
julia> [ch => i for (i, ch) in enumerate(chars)]
3-element Vector{Pair{Char, Int64}}:
'a' => 1
'b' => 2
'c' => 3

Conclusion

map(x -> x.foo, objects)
map(foo, objects)

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store