Professional Documents
Culture Documents
4.functions Over Recursive Datatypes - Reading 2 - Recursive Data Types - 6.005.2x Courseware - EdX
4.functions Over Recursive Datatypes - Reading 2 - Recursive Data Types - 6.005.2x Courseware - EdX
2x Courseware | edX
For example, consider the size of the list, which is certainly an operation we'll want in
ImList. We can de ne it like this:
and then fully specify its meaning by de ning size for each variant of ImList:
size(Empty) = 0
size(Cons( rst: E, rest: ImList)) = 1 + size(rest)
This function is recursive. We can think about the execution of size on a particular list
as a series of reduction steps:
https://courses.edx.org/courses/course-v1:MITx+6.005.2x+1T2017/courseware/Readings/02-Recursive-Data-Types/?child=first 1/4
5/10/2020 Functions over recursive datatypes | Reading 2: Recursive Data Types | 6.005.2x Courseware | edX
And the cases from the de nition can be translated directly into Java as methods in
ImList, Empty, and Cons:
is a very common and practical design pattern. It sometimes goes by the unhelpful
name interpreter pattern.
https://courses.edx.org/courses/course-v1:MITx+6.005.2x+1T2017/courseware/Readings/02-Recursive-Data-Types/?child=first 2/4
5/10/2020 Functions over recursive datatypes | Reading 2: Recursive Data Types | 6.005.2x Courseware | edX
isEmpty(Empty) = true
isEmpty(Cons( rst: E, rest: ImList)) = false
contains(Empty, e: E) = false
contains(Cons( rst: E, rest: ImList), e: E) = ( rst = e) ∨ contains(rest, e)
reverse(Empty) = empty()
reverse(Cons( rst: E, rest: ImList)) = append(reverse(rest), cons( rst, empty())
For reverse, it turns out that the recursive de nition produces a pretty bad
implementation in Java, with performance that's quadratic in the length of the list
you're reversing. We could rewrite it using an iterative approach if needed.
https://courses.edx.org/courses/course-v1:MITx+6.005.2x+1T2017/courseware/Readings/02-Recursive-Data-Types/?child=first 3/4
5/10/2020 Functions over recursive datatypes | Reading 2: Recursive Data Types | 6.005.2x Courseware | edX
append 6
I am trying to implement the append function, but I can't gure out how to do it without reversin…
https://courses.edx.org/courses/course-v1:MITx+6.005.2x+1T2017/courseware/Readings/02-Recursive-Data-Types/?child=first 4/4