# 如何在ABAP里用函数式编程思想打印出非波拉契Fibonacci（数列）

REPORT Z_FIBO.

PARAMETERS: N type i,

v1 RADIOBUTTON GROUP v default 'X',

data: f type i,

t type i.

data: product_guid type comm_product-product_guid.

get run time field t.

case 'X'.

when v1\. perform fibonacci using n changing f.

when v2\. perform fibonacci_2 using n changing f.

endcase.

write: / 'Fibonacci(', n, ') =', f.

get run time field t.

write: / 'Runtime', t, 'microseconds'.

*&---------------------------------------------------------------------*

*& Form fibonacci

*&---------------------------------------------------------------------*

form fibonacci using in type i

changing fib type i.

data: f_1 type i, f_2 type i,

n_1 type i, n_2 type i.

case in.

when 0\. fib = 1.

when 1\. fib = 1.

when others.

n_1 = in - 1.

n_2 = in - 2.

perform fibonacci using n_1 changing f_1.

perform fibonacci using n_2 changing f_2.

fib = f_1 + f_2.

endcase.

endform. "fibonacci

*&---------------------------------------------------------------------*

*& Form fibonacci_2

*&---------------------------------------------------------------------*

form fibonacci_2 using in type i

changing fib type i.

data: f_1 type i, f_2 type i,

n_1 type i, n_2 type i,

l type i.

data: fibo type table of i.

append 1 to fibo. " fibonacci(0)

append 1 to fibo. " fibonacci(1)

n_1 = 1.

n_2 = 2.

l = in - 1.

do l times.

read table fibo index n_1 into f_1.

read table fibo index n_2 into f_2.

fib = f_1 + f_2.

append fib to fibo.

enddo.

endform. "fibonacci_2

REPORT z.

CLASS lcl_fibonacci DEFINITION.

PUBLIC SECTION.

TYPES: zint_tab TYPE TABLE OF int4 WITH EMPTY KEY.

METHODS fibonacci

IMPORTING !n TYPE i RETURNING VALUE(fib_numbers) TYPE zint_tab.

ENDCLASS.

CLASS lcl_fibonacci IMPLEMENTATION.

METHOD fibonacci.

fib_numbers = COND #( WHEN n = 0

THEN VALUE #( ( |0| ) )

WHEN n = 1

THEN VALUE #( ( |0| ) ( |1| ) )

ELSE

VALUE #( LET fn1 = fibonacci( n - 1 )

x = fn1[ lines( fn1 ) ]

y = fn1[ lines( fn1 ) - 1 ]

IN ( LINES OF fn1 ) ( x + y ) ) ).

ENDMETHOD.

ENDCLASS.

START-OF-SELECTION.

cl_demo_output=>display( NEW lcl_fibonacci( )->fibonacci( 10 ) ).

|
JavaScript 前端开发 Java

115 0
|
JavaScript 前端开发 Java

107 0

82 0

95 0

155 0
|
2月前
|

38 0
|
2月前
|
BI

34 0
|
2月前
|

SAP ABAP CALL SUBSCREEN 代码解析
SAP ABAP CALL SUBSCREEN 代码解析
84 0
|
2月前
|

ABAP 如何把 unicode 代码点转换成字符
ABAP 如何把 unicode 代码点转换成字符
34 0
|
2月前
|

36 0