如果您将列表视为“数据集”或“表”,并将列表中的每个元素视为“行”,并将元素的数据类型的定义视为“属性”的枚举,那么您会做什么得到是一种“投影”从关系代数的意义上来说:https://en.wikipedia.org/wiki/Projection_(关系代数) https://en.wikipedia.org/wiki/Projection_(relational_algebra) .
这是一个 Scala 示例,感觉有点像 SQL:
case class Row(id: Int, name: String, surname: String, age: Int)
val data = List(
Row(0, "Bob", "Smith", 25),
Row(1, "Charles", "Miller", 35),
Row(2, "Drew", "Shephard", 45),
Row(3, "Evan", "Bishop", 55)
)
val surnames = data map (_.surname)
val ages = data map (_.age)
val selectIdName = data map { row => (row.id, row.name) }
println(surnames)
// List(Smith, Miller, Shephard, Bishop)
println(selectIdName)
// List((0,Bob), (1,Charles), (2,Drew), (3,Evan))
Here, _.fieldName
是类型的内联函数文字的简短语法Row => TypeOfTheField
.
在 Haskell 中,这有点微不足道,因为记录数据类型的声明会自动将所有 getter 函数带入作用域:
data Row = Row { id :: Int
, name :: String
, surname :: String
, age :: Int
} deriving Show
main = let dataset = [ Row 0 "Bob" "Smith" 25
, Row 1 "Charles" "Miller" 35
, Row 2 "Drew" "Shephard" 45
, Row 3 "Evan" "Bishop" 55
]
in print $ map name dataset
-- prints ["Bob","Charles","Drew","Evan"]
甚至 Java 从版本 8 开始也有类似的东西:
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
class JavaProjectionExample {
private static class Row {
private final int id;
private final String name;
private final String surname;
private final int age;
public Row(int id, String name, String surname, int age) {
super();
this.id = id;
this.name = name;
this.surname = surname;
this.age = age;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String getSurname() {
return this.surname;
}
public int getAge() {
return this.age;
}
}
public static void main(String[] args) {
List<Row> data = Arrays.asList(
new Row(0, "Bob", "Smith", 25),
new Row(1, "Charles", "Miller", 35),
new Row(2, "Drew", "Shephard", 45),
new Row(3, "Evan", "Bishop", 55)
);
List<Integer> ids = data.stream().map(Row::getId).collect(toList());
List<String> names = data.stream().map(Row::getName).collect(toList());
System.out.println(ids);
System.out.println(names);
}
}
Here, Row::getterName
是 getter 方法的特殊语法,它是一个类型的值Function<Row, FieldType>
.