Created
November 5, 2012 00:24
-
-
Save keithrbennett/4014532 to your computer and use it in GitHub Desktop.
Functional Programming Playground With Ruby
This file contains hidden or 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
| #!/usr/bin/env ruby | |
| LINE_SEPARATOR = '-' * 79 | |
| # Currying - using a function that takes n parameters, | |
| # create a new function that call it, providing some of those | |
| # parameters so that it requires < n parameters | |
| # (e.g. double for mult, square for power below): | |
| mult = ->(multiplier) { ->(n) { multiplier * n } } | |
| double = mult.(2) | |
| puts "double of 3 is #{double.(3)}" | |
| power = ->(exponent) { ->(n) { n ** exponent } } | |
| square = power.(2) | |
| puts "square of 8 is #{square.(8)}" | |
| square_root = power.(0.5) | |
| puts "The square root of 9 is #{ square_root.(9)}" | |
| # Chaining Functions Together | |
| chain = ->(*procs) { ->(x) { procs.inject(x) { |x, proc| proc.(x) } } } | |
| double_then_square = chain.(double, square) | |
| puts "3 doubled then squared is #{double_then_square.(3)}" | |
| add = ->(*numbers) { numbers.inject(:+) } | |
| puts "1 + 2 + 3 = #{add.(1, 2, 3)}" | |
| hypoteneuse = ->(a, b) { square_root.(square.(a) + square.(b)) } | |
| puts "The hypoteneuse of a triangle with sides 3 and 4 is #{hypoteneuse.(3, 4)}" | |
| read_file_lines = ->(filespec) { File.readlines(filespec) } | |
| firster = ->(object) { object.first } | |
| first_line = firster.(read_file_lines.(__FILE__)) | |
| puts "#{LINE_SEPARATOR}\nThis script's first line is:\n#{first_line}" | |
| file_writer = ->(filespec, contents) { File.write(filespec, contents) } | |
| file_writer.('favorites.txt', "fruit,mango") | |
| parse_csv = ->(string) { string.split(',') } | |
| Favorite = Struct.new(:type, :instance) | |
| parse_favorite = ->(string) { | |
| fav = Favorite.new | |
| fav.type, fav.instance = *parse_csv.(string) | |
| fav | |
| } | |
| puts "#{LINE_SEPARATOR}\nParser parses to: #{parse_favorite.('fruit,mango')}" | |
| format_favorite = ->(favorite) { "Favorite #{favorite.type} is #{favorite.instance}" } | |
| # Putting it all together into a transformation chain: | |
| # Read the first line from the favorites.txt file, parse it | |
| # into a Favorite instance, and apply the formatter to it: | |
| transformations = [ | |
| read_file_lines, | |
| firster, | |
| parse_favorite, | |
| format_favorite | |
| ] | |
| transform_chain = chain.(*transformations) | |
| result = transform_chain.('favorites.txt') | |
| puts "#{LINE_SEPARATOR}\nUsing transform chain, we get:\n#{result}." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment