JavaFX教程-查询数组

上一篇 / 下一篇  2008-03-18 16:49:46 / 个人分类:Javafx

像在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;
	}

TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2010-03-21  
 123456
78910111213
14151617181920
21222324252627
28293031   

数据统计

  • 访问量: 60400
  • 日志数: 171
  • 影音数: 3
  • 建立时间: 2008-02-28
  • 更新时间: 2008-05-19

RSS订阅

Open Toolbar