This document provides an overview of functional programming concepts in Ruby. It discusses the history and advantages of functional programming, comparing the functional and object-oriented paradigms. It introduces functional programming concepts like pure functions, recursion, immutable data, and higher-order functions. It demonstrates how these concepts can be applied in Ruby using functions, closures, currying, composition, and the Enumerable module. Overall, the document serves as a high-level introduction to thinking functionally in Ruby.
Inspired by Josh Bloch's Java Puzzlers, we put together our own Python Puzzlers. This slide deck brings you a set of 10 python puzzlers, that are fun and educational. Each puzzler will show you a piece of python code. Your task if to figure out what happens when the code is run. Whether you're a python beginner or a passionate python veteran, we hope that there's something to learn for everybody.
This slide deck was first presented at shopkick. Nandan Sawant and Ryan Rueth are engineers at shopkick. Keeping the audience in mind, most of the puzzlers are based on python 2.x.
Following a game show format made popular by Joshua Bloch and Neal Gafter's Java Puzzlers this presentation intends to both entertain and inform. Snippets of Python code the whose behaviour is not entirely obvious are shown, the audience will then be asked to pick from a number of options what the behaviour of the program is. The correct and sometimes non-intuitive answer will then be given along with a brief explanation of the idea the puzzle exposes. Only a modest working knowledge of the Python language is required to understand the puzzles, but the puzzles may also entertain the more experienced Python programmer.
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
Very interesting C programming Technical Questions Vanathi24
This power point explains about some interesting interview technical questions from C programming. All the programs are explained with detailed necessary information.
Chapter 22. Lambda Expressions and LINQIntro C# Book
In this chapter we will become acquainted with some of the advanced capabilities of the C# language. To be more specific, we will pay attention on how to make queries to collections, using lambda expressions and LINQ, and how to add functionality to already created classes, using extension methods. We will get to know the anonymous types, describe their usage briefly and discuss lambda expressions and show in practice how most of the built-in lambda functions work. Afterwards, we will pay more attention to the LINQ syntax – we will learn what it is, how it works and what queries we can build with it. In the end, we will get to know the meaning of the keywords in LINQ, and demonstrate their capabilities with lots of examples.
Inspired by Josh Bloch's Java Puzzlers, we put together our own Python Puzzlers. This slide deck brings you a set of 10 python puzzlers, that are fun and educational. Each puzzler will show you a piece of python code. Your task if to figure out what happens when the code is run. Whether you're a python beginner or a passionate python veteran, we hope that there's something to learn for everybody.
This slide deck was first presented at shopkick. Nandan Sawant and Ryan Rueth are engineers at shopkick. Keeping the audience in mind, most of the puzzlers are based on python 2.x.
Following a game show format made popular by Joshua Bloch and Neal Gafter's Java Puzzlers this presentation intends to both entertain and inform. Snippets of Python code the whose behaviour is not entirely obvious are shown, the audience will then be asked to pick from a number of options what the behaviour of the program is. The correct and sometimes non-intuitive answer will then be given along with a brief explanation of the idea the puzzle exposes. Only a modest working knowledge of the Python language is required to understand the puzzles, but the puzzles may also entertain the more experienced Python programmer.
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
Very interesting C programming Technical Questions Vanathi24
This power point explains about some interesting interview technical questions from C programming. All the programs are explained with detailed necessary information.
Chapter 22. Lambda Expressions and LINQIntro C# Book
In this chapter we will become acquainted with some of the advanced capabilities of the C# language. To be more specific, we will pay attention on how to make queries to collections, using lambda expressions and LINQ, and how to add functionality to already created classes, using extension methods. We will get to know the anonymous types, describe their usage briefly and discuss lambda expressions and show in practice how most of the built-in lambda functions work. Afterwards, we will pay more attention to the LINQ syntax – we will learn what it is, how it works and what queries we can build with it. In the end, we will get to know the meaning of the keywords in LINQ, and demonstrate their capabilities with lots of examples.
Regular expressions are used to identify whether a pattern exists in a given sequence of characters (string) or not. They help in manipulating textual data, which is often a pre-requisite for data science projects that involve text mining. You must have come across some application of regular expressions: they are used at the server side to validate the format of email addresses or password during registration, used for parsing text data files to find, replace or delete certain string, etc.
The Key Difference between a List and a Tuple. The main difference between lists and a tuples is the fact that lists are mutable whereas tuples are immutable. A mutable data type means that a python object of this type can be modified. Let's create a list and assign it to a variable.
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.
A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.
In this chapter we will explore strings. We are going to explain how they are implemented in Java and in what way we can process text content. Additionally, we will go through different methods for manipulating a text: we will learn how to compare strings, how to search for substrings, how to extract substrings upon previously settled parameters and last but not least how to split a string by separator chars. We will demonstrate how to correctly build strings with the StringBuilder class. We will provide a short but very useful information for the most commonly used regular expressions.
Class 12 Computer Science, Chapter 4 - Using Python Libraries. Self learning Presentation in the form of Teacher - Student conversation.
Size 20.1 MB ppt format is also available at the same site Size 5.4 MB
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
Regular expressions are used to identify whether a pattern exists in a given sequence of characters (string) or not. They help in manipulating textual data, which is often a pre-requisite for data science projects that involve text mining. You must have come across some application of regular expressions: they are used at the server side to validate the format of email addresses or password during registration, used for parsing text data files to find, replace or delete certain string, etc.
The Key Difference between a List and a Tuple. The main difference between lists and a tuples is the fact that lists are mutable whereas tuples are immutable. A mutable data type means that a python object of this type can be modified. Let's create a list and assign it to a variable.
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a ‘comma’.
A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.
In this chapter we will explore strings. We are going to explain how they are implemented in Java and in what way we can process text content. Additionally, we will go through different methods for manipulating a text: we will learn how to compare strings, how to search for substrings, how to extract substrings upon previously settled parameters and last but not least how to split a string by separator chars. We will demonstrate how to correctly build strings with the StringBuilder class. We will provide a short but very useful information for the most commonly used regular expressions.
Class 12 Computer Science, Chapter 4 - Using Python Libraries. Self learning Presentation in the form of Teacher - Student conversation.
Size 20.1 MB ppt format is also available at the same site Size 5.4 MB
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
C++ это мультипарадигменный язык, поэтому программист сам может выбирать и совмещать структурный, объектно-ориентированный, обобщенный и функциональный подходы. Функциональный аспект C++ особенно расширился стандартом C++11: лямбда-функции, variadic templates, std::function, std::bind. (язык доклада: английский).
Using functional concepts in Python. Introduction to functional programming and exploring each of the concepts, like map, filter and reduce in detail and how functional programming can help creating massively parallel software systems
INFORMATIVE ESSAYThe purpose of the Informative Essay assignme.docxcarliotwaycave
INFORMATIVE ESSAY
The purpose of the Informative Essay assignment is to choose a job or task that you know how to do and then write a minimum of 2 full pages, maximum of 3 full pages, Informative Essay teaching the reader how to do that job or task. You will follow the organization techniques explained in Unit 6.
Here are the details:
1. Read the Lecture Notes in Unit 6. You may also find the information in Chapter 10.5 in our text on Process Analysis helpful. The lecture notes will really be the most important to read in writing this assignment. However, here is a link to that chapter that you may look at in addition to the lecture notes:
https://open.lib.umn.edu/writingforsuccess/chapter/10-5-process-analysis/ (Links to an external site.)
2. Choose your topic, that is, the job or task you want to teach. As the notes explain, this should be a job or task that you already know how to do, and it should be something you can do well. At this point, think about your audience (reader). Will your reader need any knowledge or experience to do this job or task, or will you write these instructions for a general reader where no experience is required to perform the job?
3. Plan your outline to organize this essay. Unit 6 notes offer advice on this organization process. Be sure to include an introductory paragraph that has the four main points presented in the lecture notes.
4. Write the essay. It will need to be at least 2 FULL pages long, maximum of 3 full pages long. You will use the MLA formatting that you used in previous essays from Units 3, 4, and 5.
5. Be sure to include a title for your essay.
6. After writing the essay, be sure to take time to read it several times for revision and editing. It would be helpful to have at least one other person proofread it as well before submitting the assignment.
Quiz2
# comments start with #
# to quit q()
# two steps to install any library
#install.packages("rattle")
#library(rattle)
setwd("D:/AJITH/CUMBERLANDS/Ph.D/SEMESTER 3/Data Science & Big Data Analy (ITS-836-51)/RStudio/Week2")
getwd()
x <- 3 # x is a vector of length 1
print(x)
v1 <- c(2,4,6,8,10)
print(v1)
print(v1[3])
v <- c(1:10) #creates a vector of 10 elements numbered 1 through 10. More complicated data
print(v)
print(v[6])
# Import test data
test<-read.csv("CVEs.csv")
test1<-read.csv("CVEs.csv", sep=",")
test2<-read.table("CVEs.csv", sep=",")
write.csv(test2, file="out.csv")
# Write CSV in R
write.table(test1, file = "out1.csv",row.names=TRUE, na="",col.names=TRUE, sep=",")
head(test)
tail(test)
summary(test)
head <- head(test)
tail <- tail(test)
cor(test$X, test$index)
sd(test$index)
var(test$index)
plot(test$index)
hist(test$index)
str(test$index)
quit()
Quiz3
setwd("C:/Users/ialsmadi/Desktop/University_of_Cumberlands/Lectures/Week2/RScripts")
getwd()
# Import test data
data<-read.csv("yearly_sales.csv")
#A 5-number summary is a set of 5 descriptive statistics for summarizing a continuous univariate data set.
#It consists o ...
A few techniques for everyday Ruby hacking
Touching on the following topics:
DRY Assignment
Ternary operator
Bang bang
Conditional assignment
Parallel assignment
Multiple return
Implied begin
Exception lists
Symbol to Proc
MapReduce
Regex captures
tap
sprintf
case equality
Splat Array
Splat args
blank?
present?
presence
truncate
try
in?
Delegation
delegate
Memoization
memoize
alias_method_chain
class_attribute
HashWithIndifferentAccess
Installing and Using Python
Basic I/O
Variables and Expressions
Conditional Code
Functions
Loops and Iteration
Python Data Structures
Errors and Exceptions
Object Oriented with Python
Multithreaded Programming with Python
Install/Create and Using Python Library
Compile Python Script
Resources
===========================
and 7 Quizzes
Functional programming languages promise to be easier to test and easier to debug. However, when learning the functional way we often try to translate our current techniques to another language. This is usually not easy and the end result is far from those promises we've heard. Early frustrations might even discourage from further learning.
In this talk I will show you two very simple patterns:
- Designing code around single data structure
- Dealing with impure parts of program like DBs, external services or IO
This should give beginners jump start for their first toy projects and further exploration.
Ejercicios de estilo en la programaciónSoftware Guru
El escritor francés Raymond Queneau escribió a mediados del siglo XX un libro llamado "Ejercicios de Estilo" donde mostraba una misma historia corta, redactada de 99 formas distintas.
En esta plática realizaremos el mismo ejercicio con un programa de software. Abarcaremos distintos estilos y paradigmas: programación monolítica, orientada a objetos, relacional, orientada a aspectos, monadas, map-reduce, y muchos otros, a través de los cuales podremos apreciar la riqueza del pensamiento humano aplicado a la computación.
Esto va mucho más allá de un ejercicio académico; el diseño de sistemas de gran escala se alimenta de esta variedad de estilos. También platicaremos sobre los peligros de quedar atrapado bajo un conjunto reducido de estilos a lo largo de tu carrera, y la necesidad de verdaderamente entender distintos estilos al diseñar arquitecturas de sistemas de software.
Semblanza del conferencista:
Crista Lopez es profesora en la Facultad de Ciencias Computacionales de la Universidad de California en Irvine. Su investigación se enfoca en prácticas de ingeniería de software para sistemas de gran escala. Previamente, fue miembro fundador del equipo en Xerox PARC creador del paradigma de programación orientado a aspectos (AOP). Crista es una de las desarrolladoras principales de OpenSimulator, una plataforma open source para crear mundos virtuales 3D. También es fundadora de Encitra, empresa especializada en la utilización de la realidad virtual para proyectos de desarrollo urbano sustentable. @cristalopes
After 10 years of Object Orientated Java, 2 years of Functional Programming in Scala was enough to convince me that I could never switch back. But why? The answer is simple: Functional Scala lets you think less. It reduces the number of moving parts you need to hold in your head, lets you stay focussed and saves your mental stack from overflowing.
In this talk I'll show you how to stop treating Scala as a better Java and start exploring the world of Functional Programming. I'll use code examples to demonstrate a four step path that'll let you ease yourself into the world of Functional Programming while continuing to deliver production quality code.
With each step we'll learn a new technique, and understand how it leaves you with less to think about: Hopefully this talk will convince you that Functional Scala leads to code that's easier to hold in your head, and leave you excited about learning a new paradigm.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
2. Learning FP
it’s (sometimes) (a bit) difficult (in the beginning)
- you need to retrain your brain -
but rewarding
it’s fun & productive
3. History
‣ Lambda calculus: 1930’s (Alonzo Church)
‣ Lisp: 1950’s, multi-paradigm language strongly inspired by lambda-calculus
(symbolic manipulation, rewriting)
‣ ML-family: 1970’s, general purpose functional programming language with
type inference
‣ Haskell: 1987, 1998, 2010, open standard for functional programming
research
‣ Other: Clean, F#, Scheme, Scala, Clojure, XSLT, Erlang, SQL, ...
4. Isn’t all programming functional?
‣ FP proceeds from a startling premise—that we construct programs using
only pure functions, or functions that avoid side effects like changing
variables(state), writing to a database or reading from a file.
‣ In a pure functional programming language, everything is a function. we can
pass them around and “calculate” with them (combine, evaluate or
partially evaluate, etc).
‣ A function defines a mapping from a “Domain” into the
“Codomain” (image, range)
5. Advantages
‣ No mutable data and hence:
‣ No side effects, no implicit hidden state, less bugs.
‣ No variables ! (only values) => optimizations
‣ Can (more easily) be parallelized over cpu’s (multicore), etc. => no
locks, no race conditions, no deadlocks
‣ Enables Provability (both for humans and computers)
6. FP vs OO
‣ Whereas an object-oriented mindset will foster the approach of
defining an application domain as a set of nouns (classes) [ person, ticket,
etc ]
‣ The functional mind will see the solution as the composition or verbs
(functions) [ register, sell ]
‣ Though both programmers may in all likelihood generate equivalent results, the
functional solution will be more succinct, understandable, and reusable. Grand
claims indeed!
7. Immutable Objects
‣ An OO pattern that actually originates in FP world
‣ ISO changing a data structure, don’t modify in place but create a new
object.
‣ In Ruby this is typically the default. Methods that don’t follow this principle
are assumed ‘dangerous’ and are typically marked with a ‘!’
• name.reverse => returns a new string that contains the reversed name
• name.reverse! => replaces the name with the reversed value
8. Ruby and FP
‣ Ruby is an imperative and OO language with closure support
‣ But we can apply (some) FP principles
‣ It allows to mix and match OO with FP programming style
A bit of pattern matching
‣ You can’t assume immutability ... it’s a choice • x, *xs = [1,2,3,4]
‣ No (real) pattern matching (yet) x => 1
xs => [2,3,4]
‣ No lazy evaluation (yet) • a,b,tail = [1,2,3,4]
a => 1
b => 2
tail => [3,4]
9. Recursion
# fibonacci functional through recursion
def fib(count, a = 1, b = 1 , r = []) r is the
accumulator
count == 0 ? r : fib(count-1, b, a+b, r << a)
end
fib(10) # => [1,1,2,3,5,... needs a bit of
practice but
once you get
it ...
10. or also - As opposed to ?
‣ Another look at it is to compare imperative programming languages with
declarative programming languages
‣ Imperative = emphasize on how something is computed
‣ Declarative = emphasize on what is to be computed and not on
how
‣ Imperative is counterintuitive when you’re used to imperative
programming
12. First introduce Closure
‣ Closure = an anonymous function block together with a referencing
environment
‣ Where? javascript, python, ruby, PHP, C# 2.0, java 8! :)
23. Currying
‣ In mathematics and computer science, currying is the technique of
transforming a function that takes multiple arguments (or a tuple of
arguments) in such a way that it can be called as a chain of functions, each
with a single argument (partial application). It was originated by Moses
Schönfinkel and later re-discovered by Haskell Curry.
‣ curry(int, int => bool) = int => (int => bool)
24. Functions as Values in Ruby
inc = lambda { |x| x + 1 }
inc = ->(x) { x + 1 }
inc.(4) => 5
add = lambda { |x,y| x + y }
add = ->(x,y) { x + y }
add.(2,3) => 5
25. Constants are Functions
constant = ->(c,x) { c }.curry
hello = constant.(“hello”)
hello.(1) => “hello”
hello.(“eugen”) => “hello”
26. Composition
identity = ->(x) { x } # a closure
power = ->(base, x) { base**x }.curry
sum_of = ->(f, xs, i=0) { xs.inject(i) { |a,i| a+=f.(i) } }.curry
sum_of_numbers = sum_of.(identity)
a Higher Order
sum_of_power2s = sum_of.(power.(2)) function takes a
sum_of_squares = sum_of.(square) function as
parameter
# usage
sum_of_numbers.(0..10) # => 55
sum_of_squares.(0..10) # => 2047
sum_of.( power.(3) ).(0..10) # => 88573
27. Constants are Functions
constant = ->(c,x) { c }.curry
sum_of = ->(f, r, i=0) { r.inject(i) { |a,i| a+=f.(i) } }.curry
word_count = sum_of.( constant.(1) )
word_count.( %w(welcome to the world of fp) ) => 6
37. Imperative Liquer
def cheap_boose_nearby (liquer_stores)
min = liquer_stores[0][:price]
liquer_stores.each do |store|
if store[:d] < 5.0 then
price = store[:price]
price = price * 0.9 if store[:name] == "shell"
min = price if price < min
end
end
min
end
38. Declarative Liquer
def expensive_boose_nearby (liquer_stores)
nearby = ->(d, x) { x[:d] < d }.curry
near = nearby.(5.0)
myPrice = ->(x) {
x[:name] == "shell" ? x[:price]*0.9 : x[:price]
}
liquer_stores.
find_all(&near). recognize
collect(&myPrice). SQL ?
max
end
39. Generators / Sequence / Infinite ...
# Functions that return a sequence of values
# Here: fibonacci as infinite yielder
fibonacci = Enumerator.new do |list|
a = b = 1
loop { list.yield a; a,b = b,a+b }
end
fibonacci.take(10) # [1, .. , 55]
fibonacci.take(15) # [1, .. , 377, 610]
40. Enumerable as Class
class Fibs
include Enumerable
def each
a = b = 1;
loop { yield a; a,b = b,a+b };
end
end
Fibs.new.take(10)