@@ -1095,8 +1095,9 @@ impl<A, S, D> ArrayBase<S, D> where S: Data<Elem=A>, D: Dimension
1095
1095
init
1096
1096
}
1097
1097
1098
- /// Apply `f` elementwise and return a new array with
1099
- /// the results.
1098
+ /// Create a new array with the results of applying `f` on a reference
1099
+ /// to each element.
1100
+ /// Elements are visited in arbitrary order.
1100
1101
///
1101
1102
/// Return an array with the same shape as *self*.
1102
1103
///
@@ -1128,4 +1129,83 @@ impl<A, S, D> ArrayBase<S, D> where S: Data<Elem=A>, D: Dimension
1128
1129
}
1129
1130
}
1130
1131
}
1132
+
1133
+ /// Create a new array with the results of applying `f` on the value of
1134
+ /// each element.
1135
+ /// Elements are visited in arbitrary order.
1136
+ ///
1137
+ /// Return an array with the same shape as *self*.
1138
+ ///
1139
+ /// ```
1140
+ /// use ndarray::arr2;
1141
+ ///
1142
+ /// let a = arr2(&[[ 0., 1.],
1143
+ /// [-1., 2.]]);
1144
+ /// assert!(
1145
+ /// a.mapv(f32::abs) == arr2(&[[0., 1.],
1146
+ /// [1., 2.]])
1147
+ /// );
1148
+ /// ```
1149
+ pub fn mapv < B , F > ( & self , mut f : F ) -> OwnedArray < B , D >
1150
+ where F : FnMut ( A ) -> B ,
1151
+ A : Clone ,
1152
+ {
1153
+ self . map ( move |x| f ( x. clone ( ) ) )
1154
+ }
1155
+
1156
+ /// Modify the array in place by calling `f` with a mutable reference
1157
+ /// to each element.
1158
+ /// Elements are visited in arbitrary order.
1159
+ pub fn apply < F > ( & mut self , f : F )
1160
+ where S : DataMut ,
1161
+ F : FnMut ( & mut A ) ,
1162
+ {
1163
+ self . unordered_foreach_mut ( f) ;
1164
+ }
1165
+
1166
+ /// Modify the array in place by calling a function `f` that maps
1167
+ /// each element by value (from `A` to `A`).
1168
+ /// Elements are visited in arbitrary order.
1169
+ ///
1170
+ /// ```
1171
+ /// use ndarray::arr2;
1172
+ ///
1173
+ /// let mut a = arr2(&[[ 0., 1.],
1174
+ /// [-1., 2.]]);
1175
+ /// a.applyv(f32::exp);
1176
+ /// ```
1177
+ pub fn applyv < F > ( & mut self , mut f : F )
1178
+ where S : DataMut ,
1179
+ F : FnMut ( A ) -> A ,
1180
+ A : Clone ,
1181
+ {
1182
+ self . unordered_foreach_mut ( move |x| * x = f ( x. clone ( ) ) ) ;
1183
+ }
1184
+
1185
+ /// Visit each element in the array by calling `f` with a reference
1186
+ /// to each element.
1187
+ /// Elements are visited in arbitrary order.
1188
+ pub fn visit < ' a , F > ( & ' a self , mut f : F )
1189
+ where F : FnMut ( & A ) ,
1190
+ A : ' a ,
1191
+ {
1192
+ if let Some ( slc) = self . as_slice_memory_order ( ) {
1193
+ // FIXME: Use for loop when slice iterator is perf is restored
1194
+ for i in 0 ..slc. len ( ) {
1195
+ f ( & slc[ i] ) ;
1196
+ }
1197
+ } else {
1198
+ for row in self . inner_iter ( ) {
1199
+ if let Some ( slc) = row. into_slice ( ) {
1200
+ for i in 0 ..slc. len ( ) {
1201
+ f ( & slc[ i] ) ;
1202
+ }
1203
+ } else {
1204
+ for elt in row {
1205
+ f ( elt) ;
1206
+ }
1207
+ }
1208
+ }
1209
+ }
1210
+ }
1131
1211
}
0 commit comments