Section 3.2: Recursively Defined Functions and Procedures: A Recursive Function (Or Procedure) Calls Itself!
Section 3.2: Recursively Defined Functions and Procedures: A Recursive Function (Or Procedure) Calls Itself!
Here is a definition:
cat(,t) = t
cat(ax,t) = acat(x,t)
Approach:
Let f(<>) = 0 and f(<x>) = 0. Then for n2 we can write:
f(<x1, , xn>)
= x1x2 + x2x3 + + xn-1xn
= x1x2 + (x2x3 + + xn-1xn)
= x1x2 + f(<x2, , xn>)
So here is our recursive definition:
f(<>) = 0
f(<x>) = 0
f(h::t) = hhead(t) + f(t).
Solution:
isin(x,<>) = false
isin(x,x::t) = true
isin(x,y::t) = isin(x,t), where x y
isin(x,L) = if L=<>
then
false
else
if x=head(L)
then
true
else
isin(x,tail(L))
endIf
endIf
CS340-Discrete Structures Section 3.2 Page 7
Example: Find a recursive definition for the function
isin : A lists(A) {true,false}
where isin(x,L) means that x occurs in the list L.
Solution:
isin(x,<>) = false
isin(x,x::t) = true
isin(x,y::t) = isin(x,t), where x y
isin(x,L) = if L=<>
then
false
else
x=head(L) or isin(x,tail(L))
endIf
b c Solution:
pre-order:
in-order:
d e
post-order:
Solution:
post(<>) = <>
post(<L,x,R>) = cat(post(L),cat(post(R),<x>)
The function cat will concatenate two lists, and can be defined as:
cat(<>,L) = L
cat(h::t,L) = h::cat(t,L)
Solution:
sumnodes(<>) = 0
sumnodes(<L,x,R>) = x + sumnodes(L) + sumnodes(R)
Example: How do we obtain the sequence <x, x3, x5, x7, >?
Example: How do we obtain the sequence <1, x2, x4, x6, x8, >?