跳轉到內容

環/教程/函數語言程式設計

來自華夏公益教科書
<

函數語言程式設計

[編輯 | 編輯原始碼]

在之前的章節中,我們學習了函式和遞迴。

在本章中,我們將學習更多函數語言程式設計 (FP) 概念,例如

  • 純函式
  • 一等函式
  • 高階函式
  • 匿名函式和巢狀函式。
  • 函式的相等性



純函式

[編輯 | 編輯原始碼]

我們可以透過賦值運算子按值複製變數(列表和物件)來建立純函式(不改變狀態的函式),而不是透過引用操作傳遞給函式的原始資料。


示例

	Func Main
		aList = [1,2,3,4,5]
		aList2 = square(aList)
		see "aList" + nl
		see aList
		see "aList2" + nl
		see aList2

	Func Square aPara
		a1 = aPara		# copy the list
		for x in a1
			x *= x
		next
		return a1		# return new list

輸出

	aList
	1
	2
	3
	4
	5
	aList2
	1
	4
	9
	16
	25

一等函式

[編輯 | 編輯原始碼]

環程式語言中的函式是一等公民,您可以將函式作為引數傳遞,將它們作為返回值,或者將它們儲存在變數中。

我們可以透過鍵入函式名稱作為文字(例如“FunctionName”)或 :FunctionName 來傳遞/返回函式。

我們可以使用包含函式名稱的變數來傳遞/返回函式。

我們可以使用 Call 命令從包含函式名稱的變數中呼叫函式。

語法

	Call Variable([Parameters])

示例

	Func Main
		see "before test2()" + nl
		f = Test2(:Test)
		see "after test2()" + nl
		call f()

	Func Test
		see "Message from test!" + nl

	Func Test2 f1
		call f1()
		See "Message from test2!" + nl
		return f1

輸出

	before test2()
	Message from test!
	Message from test2!
	after test2()
	Message from test!

高階函式

[編輯 | 編輯原始碼]

高階函式是將其他函式作為引數的函式。

示例

	Func Main
		times(5,:test)

	Func Test
		see "Message from the test function!" + nl

	Func Times nCount,F

		for x = 1 to nCount
			Call F()
		next

輸出

	Message from the test function!
	Message from the test function!
	Message from the test function!
	Message from the test function!
	Message from the test function!

匿名函式和巢狀函式

[編輯 | 編輯原始碼]

匿名函式是無名的函式,可以作為引數傳遞給其他函式或儲存在變數中。

語法

	Func [Parameters] { [statements] }

示例

	test( func x,y { 
				see "hello" + nl
				see "Sum : " + (x+y) + nl
		       } )

	new great { f1() }

	times(3, func { see "hello world" + nl } )

	func test x
		call x(3,3)
		see "wow!" + nl

	func times n,x
		for t=1 to n
			call x()
		next

	Class great
		func f1
			f2( func { see "Message from f1" + nl } )

		func f2 x
			call x()

輸出

	hello
	Sum : 6
	wow!
	Message from f1
	hello world
	hello world
	hello world

示例

	Func Main
		aList = [1,2,3,4]
		Map (aList , func x { 
					return x*x 
				    } )
		see aList
		aList = [4,9,14,25]
		Map(aList, :myfilter )
		see aList
		aList = [11,12,13,14]
		Map (aList , func x {
			if x%2=0
				return "even"
			else
				return "odd"
			ok
		})
		see aList

	Func myfilter x
		if x = 9
			return "True"
		else
			return "False"
		ok

	Func Map aList,cFunc
		for x in aList
			x = call cFunc(x)
		next

輸出

	1
	4
	9
	16
	False
	True
	False
	False
	odd
	even
	odd
	even

函式的相等性

[編輯 | 編輯原始碼]

我們可以使用 '=' 或 '!=' 運算子測試函式是否相等。

示例

	f1 = func { see "hello" + nl }

	f2 = func { see "how are you?" + nl }

	f3 = f1

	call f1()
	call f2()
	call f3()

	see (f1 = f2) + nl
	see (f2 = f3) + nl
	see (f1 = f3) + nl

輸出

	hello
	how are you?
	hello
	0
	0
	1


華夏公益教科書