在数组上执行循环操作的功能方法

时间:2015-06-11 04:53:11

标签: java scala functional-programming

我目前有一个Java程序,它执行以下操作:

Paint()

我正在将其转换为Scala代码并具有:

var map = { 
    control: {},
    center: {
        latitude: xxx,
        longitude: yyy

    },
    zoom: 17,
    options: {
        mapTypeControl: mapTypeControl,
        mapTypeControlOptions: {
            style: 1, // GoogleMapApi.maps.MapTypeControlStyle.HORIZONTAL_BAR
            position: 1, // GoogleMapApi.maps.ControlPosition.TOP_LEFT
        },
        streetViewControl: false,
        zoomControl: zoomControl,
        zoomControlOptions: {
            style: 0, // google.maps.ZoomControlStyle.DEFAULT,
            position: 5, // google.maps.ControlPosition.LEFT_CENTER
        },
        scrollwheel: true,
        panControl: false,
        scaleControl: false,
        draggable: true,
        maxZoom: 20,
        minZoom: 15,
    },
    trigger: false,
    bounds: {},
    dragging: false,
    events: { 
        dragend: function() {

        },
        click: function(map, eventName, args) {

        },
        idle: function() {

        }
    },
    rebuildWindows: false,
    templateUrl: 'templates/infowindow.html'
};

有关如何使这(更多)功能的任何建议?

3 个答案:

答案 0 :(得分:7)

Array伴侣对象中有许多有用的构造函数方法,例如,根据您的情况,您可以使用tabulate

val nvars: Int = 10
val vars = Array.tabulate(nvars){ someFunction } // calls someFunction on the values 0 to nvars-1, and uses this to construct the array
vars foreach (anotherFunction) // calls anotherFunction on each entry in the array

如果anotherFunction返回结果而不仅仅是"副作用"函数,你可以通过调用map

来捕获它
val vars2 = vars map (anotherFunction) // vars2 is a new array with the results computed from applying anotherFunction to each element of vars, which is left unchanged.

答案 1 :(得分:4)

使用map。在Array上调用地图将返回一个新集合。因此,对于要应用于map的所有元素的每个函数,请调用Array两次。

一些简单的演示功能:

scala> def addOne(l: Long) = l + 1
addOne: (l: Long)Long

scala> def addTwo(l: Long) = l + 2
addTwo: (l: Long)L
使用定义的函数

map数组vars

scala> val vars = Array[Long](1,2,3,4,5,6,7,8,9,10)
vars: Array[Long] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> vars.map(addOne(_))
res0: Array[Long] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)

scala> vars.map(addOne(_)).map(addTwo(_))
res1: Array[Long] = Array(4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

另一种“功能更强大”且可能是一个很好的练习的方法是使用递归函数,该函数将函数作为参数并将传入的函数应用于List的每个元素。

scala> def fun[A](as: List[A], f: A => A): List[A] = as match {
     | case List() => List()
     | case h::t => f(h) :: fun(t, f)
     | }
fun: [A](as: List[A], f: A => A)List[A]

答案 2 :(得分:1)

考虑迭代一系列Long值,

val vars = (1L to 10L).map(someFunction).map(anotherFunction)

这会将someFunction应用于范围中的每个值,然后将每个中间结果从第一个map应用到anotherFunction。假设每个函数都采用并传递Long类型的值。

要将vars转换为所需的集合,例如ArrayList,请考虑

vars.toArray
vars.toList

使用view一次将两个函数应用于范围中的每个值,因此无需从映射someFunction创建中间集合,

(1L to 10L).view.map(someFunction).map(anotherFunction)
相关问题