OLD | NEW |
(Empty) | |
| 1 // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include <stdio.h> |
| 6 |
| 7 #include "base/bind.h" |
| 8 #include "base/bind_helpers.h" |
| 9 #include "base/callback.h" |
| 10 #include "base/strings/string_number_conversions.h" |
| 11 |
| 12 namespace { |
| 13 |
| 14 struct FibonacciState { |
| 15 FibonacciState() : i(0), j(1) {} |
| 16 |
| 17 int i, j; |
| 18 }; |
| 19 |
| 20 int ComputeNextFibonacciNumber(FibonacciState* state) { |
| 21 int next = state->i + state->j; |
| 22 state->i = state->j; |
| 23 state->j = next; |
| 24 return state->i; |
| 25 } |
| 26 |
| 27 base::Callback<int()> MakeFibonacciClosure() { |
| 28 scoped_ptr<FibonacciState> state(new FibonacciState); |
| 29 return base::Bind(&ComputeNextFibonacciNumber, base::Owned(state.release())); |
| 30 } |
| 31 |
| 32 } // namespace |
| 33 |
| 34 int main(int argc, char* argv[]) { |
| 35 if (argc <= 1) { |
| 36 printf("%s: missing operand\n", argv[0]); |
| 37 return -1; |
| 38 } |
| 39 |
| 40 int n = 0; |
| 41 if (!base::StringToInt(argv[1], &n) || n < 0) { |
| 42 printf("%s: invalid n `%s'\n", argv[0], argv[1]); |
| 43 return -1; |
| 44 } |
| 45 |
| 46 base::Callback<int()> fibonacci_closure1 = MakeFibonacciClosure(); |
| 47 base::Callback<int()> fibonacci_closure2 = MakeFibonacciClosure(); |
| 48 for (int i = 0; i < n; ++i) { |
| 49 int j = fibonacci_closure1.Run(); |
| 50 int k = fibonacci_closure2.Run(); |
| 51 DCHECK_EQ(j, k); |
| 52 printf("F_%d = %d\n", i, j); |
| 53 } |
| 54 |
| 55 return 0; |
| 56 } |
OLD | NEW |