-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path7. Multiple-Dispatch.jl
74 lines (45 loc) · 1.24 KB
/
7. Multiple-Dispatch.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# In Julia, all named functions are generic functions.
# This means that they are built up from many small methods.
# Each constructor for Lion is a method of the generic function Lion.
abstract Cat
type Panther <: Cat
eye_color
Panther() = new("green")
end
type Lion <: Cat
mane_color
roar::AbstractString
end
type Tiger
taillength::Float64
coatcolor
end
tigger = Tiger(3.5,"orange")
# For a non-constructor example, let's make a function meow for Lion, Panther
# and Tiger:
function meow(animal::Lion)
animal.roar # access type properties using dot notation
end
function meow(animal::Panther)
"grrr"
end
function meow(animal::Tiger)
"rawwwr"
end
# Testing the meow function
meow(tigger) # => "rawwr"
meow(Lion("brown","ROAAR")) # => "ROAAR"
meow(Panther()) # => "grrr"
# Defining a function that take type Cat
function pet_cat(cat::Cat)
println("The cat says $(meow(cat))")
end
pet_cat(Lion("orange","1"))
# Now we define function with more arguments:
function fight(t::Tiger,c::Cat)
println("The $(t.coatcolor) tiger wins!")
end
fight(tigger,Panther())
# We don't need a Tiger in order to fight
fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))")
fight(Lion("brown","Let's fight"),Panther())