- What is "Object-oriented programming", and what is "Functional programming".
- Object-oriented programming as trialism.
- Why and How "tail call optimization" is.
- Why and How "currying" is.
- The word "Monad" indicates different meanings - the one for the term of philosophy and the other for the term of Functional programming.
Fig. 2.1 (in F#)
open System;;Fig. 2.2 (in Ruby)
type Shape =
| Rectangle of double * double
| Ellipse of double * double
| Circle of double;;
let area shape =
let ellipse w h = Math.PI * w * h / 4.0
match shape with
| Rectangle(width, height) -> width * height
| Ellipse(width, height) -> ellipse width height
| Circle(radius) -> ellipse (radius * 2.0) (radius * 2.0);;
let ss = [Rectangle(5.0, 8.0);Ellipse(3.0, 4.0);Circle(3.0)];;
ss |> List.iter (fun s -> Console.WriteLine("area: {0}", area s));;
class ShapeFig. 5.5 (in F#)
def initialize(w, h)
@width = w
@height = h
end
def area
@width * @height
end
end
class Rectangle < Shape
def initialize(w, h)
super(w, h)
end
end
class Ellipse < Shape
def initialize(w, h)
super(w, h)
end
def area
Math::PI * @width * @height / 4.0
end
end
class Circle < Ellipse
def initialize(r)
super(r * 2.0, r * 2.0)
end
end
ss = [Rectangle.new(5.0, 8.0), Ellipse.new(3.0, 4.0), Circle.new(3.0)]
ss.each do |s|
puts "area: #{s.area}"
end
[<Class>]Fig. 5.7 (in Ruby)
type Shape =
val width : double
val height : double
new (w, h) = {width = w; height = h};;
[<Class>]
type Rectangle(w, h) =
inherit Shape(w, h);;
[<Class>]
type Ellipse(w, h) =
inherit Shape(w, h);;
[<Class>]
type Circle(r) =
inherit Ellipse(r*2.0, r*2.0);;
open System;;
let area (f:Shape) =
match f with
| :? Rectangle -> f.width * f.height
|_ -> Math.PI * f.width * f.height / 4.0;;
let r = Rectangle(5.0, 8.0);;
let u = Ellipse(3.0, 4.0);;
let v = Circle(3.0);;
Console.WriteLine("area: {0}", area r);;
Console.WriteLine("area: {0}", area u);;
Console.WriteLine("area: {0}", area v);;
module Measurable
def area
@width * @height
end
end
module Polygon
def vertices
4
end
end
class Rectangle
include Measurable, Polygon
def initialize(w, h)
@width = w
@height = h
end
end
class Ellipse
include Measurable
def initialize(w, h)
@width = w
@height = h
end
def area
Math::PI * super / 4.0
end
end
class Circle
include Measurable
def initialize(r)
@width = r
@height = r
end
def area
Math::PI * super
end
end
r = Rectangle.new(5.0, 8.0)
u = Ellipse.new(3.0, 4.0)
v = Circle.new(3.0)
[r, u, v].each do |m|
puts "area: #{m.area}"
end
puts "vertices: #{r.vertices}"
No comments:
Post a Comment