Mateusz Pokora
software developer @
https://twitter.com/pokorson
https://github.com/pokorson
class Car
attr_accessor :name, :speed, :color
def accelerate
@speed += 10
end
def break
@speed = 0
end
end
myCar = Car.new "Toyota" 50 "black"
myCar.accelerate
class Car
attr_accessor :name, :speed, :color
def accelerate
@speed += 10
end
def break
@speed = 0
end
end
1 myCar = Car.new "Toyota" 50 "black"
...
50 myCar.accelerate
class Car
attr_reader :name, :speed, :color
def self.accelerateCar(car)
self.new car.name, car.speed + 10, car.color
end
end
1 myCar = Car.new "Toyota" 50 "black"
...
50 acceleratedCar = Car.accelerateCar myCar
# pure
def add(a, b)
a + b
end
# not pure
def persistCar(car)
DB.save(car)
end
Przykładowe side effecty
Brak mechanizmów w samym języku w Ruby
class Car
attr_reader :name, :speed, :color, :owner
def self.accelerateCar(car)
Notifications.sendSpeedAlert car
self.new car.name, car.speed + 10, car.color
end
end
myCar = Car.new "Toyota" 50 "black" current_user
Car.accelerateCar myCar
add = -> (x, y) { x + y }
add.call(5, 10) => 15
-------------------------
# Currying
add = -> (x, y) { x + y }
createrAdder = add.curry
add5 = createAdder.call(5)
add5.call(10) => 15
class Car
attr_accessor :name, :speed, :color
def accelerate
@speed += 10
end
def slow_down
@speed -= 10
end
def stop
@speed = 0
end
end
myCar = Car.new "Toyota" 50 "black"
myCar.accelerate
.accelerate
.slowDown
.accelerate
.stop
def add5(x)
x + 5
end
def multiplyBy10(x)
x * 10
end
multiplyBy10( add5 3 ) === compose(multiplyBy10, add5).call(3)
# String -> List[String]
getWords = -> (str) { str.split(' ') }
# List[String] -> Int
listLength = -> (list) { list.length }
# String -> Int
getWordsCount = compose(
listLength,
getWords
)
getWordsCount.call("hello LRUG") => 2