Skip to content

Instantly share code, notes, and snippets.

@mayankgupta804
Forked from anonymous/functional.groovy
Created February 26, 2017 18:18
Show Gist options
  • Save mayankgupta804/1ba66e4b1602be48bf737641faa04eb8 to your computer and use it in GitHub Desktop.
Save mayankgupta804/1ba66e4b1602be48bf737641faa04eb8 to your computer and use it in GitHub Desktop.
Functional Groovy Crashcourse This short Groovy script I wrote to provide my students the most common functional programming techniques of the programming language Groovy in a very condensed form.
// Functional Groovy Crashcourse
//
// This short Groovy script I wrote to provide my students the most common functional
// programming techniques of the programming language Groovy in a very condensed form.
//
// Author: Nane Kratzke (Luebeck University of Applied Sciences)
// License: Free for every one
// Date: 22. March 2013
// Here is how you can define a list in Groovy.
list = ["This", "is", 1, "example"]
// You can iterate a list in Groovy and print it on console.
list.each { elem -> println elem }
// Two lists can be merged together like this.
l1 = [1, 2, 3]
l2 = [3, 4, 5]
println (l1 + l2) // [1, 2, 3, 3, 4, 5]
// You can check whether a list contains a value like this.
println ([1,2,3,4, "White Schaf"].contains("Black Sheep")) // false
println ([1,2,3,4, "Black Sheep"].contains("Black Sheep")) // true
// You can use ranges to define lists.
// Z.B. so:
println (1..5) // [1, 2, 3, 4, 5]
println (5..1) // [5, 4, 3, 2, 1]
println ((1..10).step(2)) // [1, 3, 5, 7, 9]
// And that is how you define variables in Groovy.
// Be aware: you do not need to specify types
a = 1 // Integers
b = true // Boolean (true, false)
c = 3.14 // Floating point
d = "String" // Strings with variable interpolation
e = 'c' // Strings without variable interpolation
// You can define mappings like this in Groovy
postalcodes = [
23560: "Bornkamp",
23562: "St. Juergen",
]
// To get all keys of a mapping do this:
postalcodes.keySet().each { key -> println key }
// To get all values of a mapping do this:
postalcodes.values().each { value -> println value }
// To get all key, value pairs of a mapping do this:
postalcodes.each { k, v -> println k + " -> " + v }
// By the way: Groovy is able to do variable interpolation in strings
// just use $ in double quoted string literals.
// Ok: PHP is able to do the same ...
postalcodes.each { k, v -> println "$k -> $v" }
// You can get the values by key of a mapping like this:
// Obvious isn't it?
println plz[23560] // "Bornkamp"
println plz[23562] // "St. Juergen"
// You can define a function in Groovy
// and assign it to a variable (this sounds crazy for a procedural programmer,
// but not for a functional one).
q = { x -> x * x }
// That is how you can apply these functions called closures.
println q(5) // 25
// You can also use closures like this:
println ({x -> x * x }(5)) // also 25
// You must not even give your parameters a name.
// Each closure has a standard parameter called it
// if nothing else is specified.
// So you can formulate your function even shorter ...
println ({ it * it }(5)) // one more time 25
// You can also define closures with more than one parameter:
add = { x, y -> x + y }
println add(12, 13) // its getting boring, one more time 25
// If you like you can define functions like in many other (procedural) programming
// languages (which is a little bit boring ...)
// You can omit the return statement in Groovy
// The value of the last expression in a closure or function block will get the return
def fac(n) {
n == 0 ? 1 : n * fac(n - 1)
}
println fac(10)
// Now it is getting interesting.
// You can provide functions/closures as parameters to other functions/closures
// Like that
facs = [1, 2, 3, 4].collect { i -> fac(i) }
println facs // fac is applied to every element of the list
// [1, 2, 6, 24]
// Now we will dive into some functional iterator functions.
// _collect_ (in most other functional programming languages mostly named _map_)
// iterates over all elements of a list and applies a provided function/closure.
// This works like that
println ([1, 2, 3, 4].collect { i -> i * i }) // [1, 4, 9, 16]
// You can use ranges and collect to created multidimensional datastructures like that
// This here produces a 3x3 matrix (or more precisley a list over 3 lists with 3 elements)
println ((1..3).collect { i -> (1..3).collect { it }}) // [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
// _findAll_ (in most other functional programming languages mostly named _filter_)
// filters all elements full filling an condition from a list
println([1,2,3,4].findAll { i -> i % 2 == 0 }) // [2, 4] (alle even values)
// _inject_ (in most other functional programming languages mostly named _fold_)
// "folds" a list of values to a single value by applying a folding function/closure.
println([1, 2, 3, 4].inject(0, { acc, e -> acc + e }))
// returns 10, the sum 1 + 2 + 3 + 4
// inject works like that:
// 0 (initial value) + 1 (head of list) = 1 and [2, 3, 4]
// 1 (closure result) + 2 (head of list) = 3 and [3, 4]
// 3 (closure result) + 3 (head of list) = 6 and [4]
// 6 (closure result) + 4 (head ofl ist) = 10 (final result) and [] (remaining empty list)
// Another helpfull function to generate list outputs is join
// It takes a list an generates a string. Each element is seperated by a provided separator
// string
println ([1,2,3,4].join(",")) // "1,2,3,4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment