Created
October 5, 2021 18:45
-
-
Save leontabak/b9560931ea0e91e6824749309e4a2d99 to your computer and use it in GitHub Desktop.
examples of currying and a closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.PrintWriter | |
import scala.io.Source | |
object Higher extends App { | |
println("Sputnik!") | |
// Here's an example of a closure. | |
// f is a function that returns a | |
// function to its caller | |
// the function g that it returns | |
// knows about the variable count | |
// that is declared in f | |
// call to g remembers what was done | |
// in the n-th call | |
def f():(Char) => Char = { | |
var count = 0 | |
def g(c:Char):Char = { | |
count += 1 | |
if( count % 5 == 0) '*' else c | |
} // g(Char) | |
g | |
} // f() | |
// I put a short text file in a folder that I named | |
// "resources" in the src/main folder of my project | |
val path = getClass.getResource( "poem.txt") | |
println( path ) | |
var poem = Source.fromFile( path.getFile, "UTF-8") | |
val verses = poem.getLines() | |
for( line <- verses ) | |
println( line ) | |
println( "\nDone with verses!\n") | |
poem = Source.fromFile( path.getFile, "UTF-8") | |
val letters = poem.iter.filter( {_.isLetter} ).map( {_.toUpper } ) | |
// Here's an example of "currying a function" | |
val offset = 3 | |
// First, define a function with 2 parameters (a Char and an Int) | |
// that returns a Char to its caller | |
val caesar:(Char, Int) => Char = | |
(letter, offset) => (((letter - 'A') + offset) % 26 + 'A').toChar | |
// Second, use that function to define a | |
// second function with 1 Int parameter that | |
// returns a function with Char parameter | |
val myCaesar: (Int) => (Char) => Char = | |
(offset:Int) => caesar(_, offset ) | |
// assign to shifter a function that | |
// has 1 Char argument and returns a | |
// Char to its caller | |
val shifter = myCaesar(3) | |
// apply that function to each character | |
// in a sequence of characters | |
val shifted = letters.map( shifter ) | |
// next, put all characters into one big string | |
// while replacing each character using f, | |
// the function that we defined with a closure | |
val y = shifted.foldLeft("") ((a:String,b:Char) => a + b).map( f ) | |
println( y ) | |
//for( c <- shifted ) | |
// println( c ) | |
println( "\nDone with letters!\n" ) | |
} // Higher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment