24-functors.student - Last time: * the iteration...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Last time: * the iteration abstraction * iterators * friends * observers vs. mutators Today: * What do we mean by "first-class" * The "stateful function" problem * Function objects ++++++++++++++++++++++++++++++++++++++++++++++++++++++ There are lots of things we can do with integers in a running program. We can: * create them * destroy them * pass them as arguments * return them as values In fact, we can do these four things with *any* type of value in the language---even types we create ourselves with the enum, struct, or class mechanisms. For any entity in a programming language, we say that the entity is "first-class" if you can do all four of these things. Unlike values, types and functions are *not* first class objects in C++. But, they can sometimes come close. The template mechanism allows us to pass types as arguments, after a fashion. The function pointer mechanism allows us to pass functions as arguments and return them as results, if we like. In particular, in the C++ language, we cannot create and destroy functions dynamically. Sometimes, that's a problem. However, C++ gives us a mechanism that is *almost* exactly like first-class functions, called "function objects". We'll illustrate the problem by using the list_t ADT from project 2 to write a generic "has-a" function using function pointers. Remember the operations on a list_t: list_t list_make(int v, list_t l); int list_first(list_t l); list_t list_rest(list_t l); bool list_isEmpty(list_t l); Given these, suppose we wanted to write the following routine: bool has_odd(list_t l); // EFFECT: returns true if l has an odd element, false otherwise The recursive definition of this function is: The empty list has no odd elements
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
A non-empty list has odd elements if the first element is odd or the rest of the list has odd elements So, the recursive definition of this function is: bool has_odd(list_t l) { if (list_isEmpty(l)) { return false; } else if (list_first(l) % 2) { return true;
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

24-functors.student - Last time: * the iteration...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online