// `std/list`: sort and sort_by (stability, a custom and an effectful // comparator), take, drop and find, on their edge cases. import std/io import std/list import std/string pub fn main :: -> () / { let xs = [3, 1, 4, 1, 5, 9, 2, 6] let empty: List = [] io.println (show (list.sort xs)) io.println (show (list.sort ["pear", "fig", "apple"])) io.println (show (list.sort empty)) io.println (show (list.sort [2])) // Descending, with a custom comparator. io.println (show (list.sort_by xs fn a b { compare b a })) // Stable: the ties on the key keep their original relative order. let pairs = [(1, "a"), (2, "b"), (1, "c"), (3, "d"), (2, "e"), (1, "f")] io.println (show (list.sort_by pairs fn x y { compare x.0 y.0 })) // The comparator may perform effects. let traced = list.sort_by [2, 1, 3] fn a b { io.println ("cmp " <> show a <> " " <> show b) compare a b } io.println (show traced) // take and drop: 0, negative, past the end, the empty list. io.println (show [list.take xs 0, list.take xs (-2), list.take xs 3, list.take xs 100]) io.println (show (list.take empty 3)) io.println ( show [ list.drop xs 0 , list.drop xs (-1) , list.drop xs 6 , list.drop xs 8 , list.drop xs 9 ] ) io.println (show (list.drop empty 2)) io.println (show (list.take xs 3 <> list.drop xs 3)) // find: a hit, a miss, the empty list. io.println (show (list.find xs fn x { x % 2 == 0 })) io.println (show (list.find [1, 3] fn x { x % 2 == 0 })) io.println (show (list.find empty fn x { x == 0 })) io.println (show (list.find ["", "a", "bc"] fn s { string.length s > 1 })) } //> [1, 1, 2, 3, 4, 5, 6, 9] //> [apple, fig, pear] //> [] //> [2] //> [9, 6, 5, 4, 3, 2, 1, 1] //> [(1, a), (1, c), (1, f), (2, b), (2, e), (3, d)] //> cmp 1 2 //> cmp 3 2 //> [1, 2, 3] //> [[], [], [3, 1, 4], [3, 1, 4, 1, 5, 9, 2, 6]] //> [] //> [[3, 1, 4, 1, 5, 9, 2, 6], [3, 1, 4, 1, 5, 9, 2, 6], [2, 6], [], []] //> [] //> [3, 1, 4, 1, 5, 9, 2, 6] //> Some(4) //> None //> None //> Some(bc)