日志 教程
当前位置: 教程  >  游戏开发  >  手机游戏开发  >  正文

JavaFX教程-查询数组

作者:郭同学 发表于 2011/9/6 23:05:08     评论(0)     阅读(4459)     
 

像在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;
评论
显示
悄悄话
汇众教育官网 | 联系方式 | 版权声明 | 友情链接
Copyright 2008© 汇众益智(北京)教育科技有限公司. All Rights Reserved
京ICP备09092043号 京公网安备11010802009023号