-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdispatch_demo.jl
More file actions
56 lines (42 loc) · 1.45 KB
/
Copy pathdispatch_demo.jl
File metadata and controls
56 lines (42 loc) · 1.45 KB
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
# --- 1. The Logic Layer (Multiple Dispatch) ---
# Using Real handles Ints, Floats, etc.
process(x::Real, y::Real) = begin
println("Logic: Adding two numbers.")
return x + y
end
# Using AbstractString handles Strings AND SubStrings
process(x::AbstractString, y::AbstractString) = begin
println("Logic: Concatenating two strings.")
return x * " " * y
end
process(x::Real, y::AbstractString) = "Error: Cannot add numeric $x to string '$y'."
process(x::AbstractString, y::Real) = process(y, x)
# --- 2. The Input Layer (Fixed Type Signature) ---
# We changed (s::String) to (s::AbstractString)
function parse_input(s::AbstractString)
# Try Integer
val_int = tryparse(Int, s)
!isnothing(val_int) && return val_int
# Try Float
val_float = tryparse(Float64, s)
!isnothing(val_float) && return val_float
# Otherwise, return the string as-is
return s
end
# --- 3. The User Interface ---
function main()
println("=== Fixed Dispatch Calculator ===")
while true
print("\nEnter Input 1 (or 'exit'): ")
raw1 = strip(readline())
raw1 == "exit" && break
print("Enter Input 2: ")
raw2 = strip(readline())
# Now parse_input accepts the SubString from strip()
val1 = parse_input(raw1)
val2 = parse_input(raw2)
result = process(val1, val2)
println("Result ($(typeof(val1)) + $(typeof(val2))): $result")
end
end
main()