You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: book/sorting.md
+39-12Lines changed: 39 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -259,27 +259,54 @@ Here's an example of a custom sort which couldn't be trivially written as a key
259
259
260
260
### Strict sort
261
261
262
-
Custom sort closures also provide a simple way to sort data while enforcing type homogeneity. This takes advantage of [operators requiring compatible data types](operators.html#types):
262
+
Custom sort closures also provides a simple way to sort data while ensuring only types with well-defined comparisons are sorted together. This takes advantage of [operators requiring compatible data types](operators.html#types):
This does not currently work with `null` values due to comparison between any value and `null` returning `null`.
282
-
:::
289
+
Special handling is required for `null` values, since comparison between any value and `null` returns `null`. To instead reject `null` values, try the following:
290
+
291
+
```nu
292
+
> let baddata = [8 3.2 null 58 2]
293
+
> let strict = {|a, b|
294
+
match [$a, $b] {
295
+
[null, _] => (error make {msg: "Attempt to sort null"}),
296
+
[_, null] => (error make {msg: "Attempt to sort null"}),
297
+
_ => ($a < $b)
298
+
}
299
+
}
300
+
> $baddata | sort-by -c $strict
301
+
Error: × Attempt to sort null
302
+
╭─[entry #3:4:21]
303
+
3 │ match [$a, $b] {
304
+
4 │ [null, _] => (error make {msg: "Attempt to sort null"}),
305
+
· ─────┬────
306
+
· ╰── originates from here
307
+
5 │ [_, null] => (error make {msg: "Attempt to sort null"}),
0 commit comments