JavaFX教程-查詢陣列

梧桐雨—168發表於2008-03-18

像在MirandaHaskell這些函數語言程式設計語言中一樣,JavaFX支援列表推導(list comprehensions),但是為了使用一種Java程式設計師更加熟悉、易懂的語法形式進行表達,JavaFX採取了selectforeach操作符。

這裡提供一個例如:

	class Album {
		attribute title: String;
		attribute artist: String;
		attribute tracks: String*;
	}

	var albums =
	[Album {
		title: "A Hard Day's Night"
		artist: "The Beatles"
		tracks:
		["A Hard Day's Night",
		"I Should Have Known Better",
		"If I Fell",
		"I'm Happy Just To Dance With You",
		"And I Love Her",
		"Tell Me Why",
		"Can't Buy Me Love",
		"Any Time At All",
		"I'll Cry Instead",
		"Things We Said Today",
		"When I Get Home",
		"You Can't Do That"]
		},
	Album {
		title: "Circle Of Love"
		artist: "Steve Miller Band"
		tracks:
		["Heart Like A Wheel",
		  "Get On Home",
		  "Baby Wanna Dance",
		  "Circle Of Love",
		  "Macho City"]
	}];

	// Get the track numbers of the albums' title tracks

	// using the select operator:

	var titleTracks =
		select indexof track + 1 from album in albums,
			track in album.tracks
				where track == album.title; // yields [1,4]

	// the same expressed using the foreach operator:

	titleTracks =
		foreach (album in albums,
			track in album.tracks
				where track == album.title)
					indexof track + 1;  // also yields [1,4]

列表推導由一個或多個輸入列表,一個可選的過濾器和一個生成器表示式組成。每個源列表與一個變數關聯。列表推導的結果是將生成器應用於滿足過濾器的源列表成員的笛卡爾乘積的子集後得到的新列表。

譯者注:這裡的過濾器指的是where子句。

列表推導為建立在列表上進行迭代遍歷的通用類提供了一種簡明的語法。

列表推導的另外一個簡單示例:

	select n*n from n in [1..100]

這個列表(順序地)包含1至100的所有數的平方值。注意上面表示式中的“n”是區域性變數。

下面的程式碼通過定義計算某個數值的所有因子的函式演示瞭如何使用過濾器:

	function factors(n) {
		return select i from i in [1..n/2] where n % i == 0;
	}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/13270562/viewspace-209690/,如需轉載,請註明出處,否則將追究法律責任。

相關文章