module scheme enum ListUtilityKind as u8 { find memp assp for_all exists filter partition remp fold_left fold_right } struct UtilityCursor { mut: value Value slow Value } fn (mut cursor UtilityCursor) advance(cycles bool, steps int) ! { if cursor.value.tag != .pair { return failure('list input was shortened during iteration') } cursor.value = cursor.value.pair_pointer().cdr if cycles && steps % 2 == 0 { if cursor.slow.tag != .pair { return failure('list input was modified during iteration') } cursor.slow = cursor.slow.pair_pointer().cdr if cursor.value.tag == .pair && cursor.value.pointer() == cursor.slow.pointer() { return failure('expected a proper list, got a circular list') } } } @[heap] struct ListUtilityState { callback Value kind ListUtilityKind mut: cursor UtilityCursor cursors []UtilityCursor rows []Value inputs int remaining int steps int pending Value accumulator Value persistent bool selected Value = nil_value() selected_tail &Pair = unsafe { nil } rejected Value = nil_value() rejected_tail &Pair = unsafe { nil } selected_suffix Value = nil_value() rejected_suffix Value = nil_value() } fn list_utility_state(value Value) &ListUtilityState { return unsafe { &ListUtilityState(value.pointer()) } } const list_utility_native_descriptors = [ NativeDescriptor{'cons*', utility_cons_star} NativeDescriptor{'remove', utility_remove} NativeDescriptor{'remv', utility_remv} NativeDescriptor{'remq', utility_remq}, ]! fn (mut vm VM) install_list_utility_primitives() { for i, name in ['find', 'memp', 'assp', 'for-all', 'exists', 'filter', 'partition', 'remp', 'fold-left', 'fold-right'] { fold := i >= int(ListUtilityKind.fold_left) variadic := fold || i in [int(ListUtilityKind.for_all), int(ListUtilityKind.exists)] function := &Function{ code: unsafe { nil } params: if fold { 3 } else { 2 } rest: variadic slot_count: 5 instructions: [bridge_instruction(.list_utility_init, i, 0), bridge_instruction(.list_utility_step, 0, 0), bridge_instruction(.list_utility_collect, 0, 0), bridge_instruction(.jump, 1, 0)] } vm.bind_global(name, procedure_value(&Procedure{ owner: vm.owner, mode: .closure, name: name, function: function })) } for index in 0 .. list_utility_native_descriptors.len { entry := &list_utility_native_descriptors[index] vm.bind_global(entry.name, procedure_value(&Procedure{ owner: vm.owner, mode: .native, name: entry.name, native: entry.callback })) } } @[direct_array_access] fn (mut m Machine) start_list_utility(kind ListUtilityKind) ! { callback := m.env.slots[0] if !callback.is_callable() { return failure('list callback must be a procedure') } mut state := &ListUtilityState{ callback: callback, kind: kind } fold := kind in [.fold_left, .fold_right] if fold || kind in [.for_all, .exists] { first := m.env.slots[if fold { 2 } else { 1 }] others := m.env.slots[if fold { 3 } else { 2 }] mut count := 1 mut tail := others for tail.tag == .pair { count++ tail = tail.pair_pointer().cdr } state.inputs = count state.cursors = filled_storage(count, UtilityCursor{}) container_store_validated(mut state.cursors, 0, UtilityCursor{ value: first slow: if fold { nil_value() } else { first } }) tail = others for i in 1 .. count { pair := tail.pair_pointer() container_store_validated(mut state.cursors, i, UtilityCursor{ value: pair.car slow: if fold { nil_value() } else { pair.car } }) tail = pair.cdr } if fold { state.accumulator = m.env.slots[1] length := first.list_length()! for i in 1 .. state.cursors.len { if state.cursors[i].value.list_length()! != length { return failure('fold lists must have equal lengths') } } state.remaining = length if kind == .fold_right { if length > max_int / count { return failure('fold inputs exceed supported size') } state.rows = value_storage(length * count) for row in 0 .. length { for column in 0 .. count { pair := state.cursors[column].value.pair_pointer() container_store_validated(mut state.rows, row * count + column, pair.car) state.cursors[column].value = pair.cdr } } state.cursors = []UtilityCursor{} } } } else { first := m.env.slots[1] state.cursor = UtilityCursor{ value: first slow: if kind in [.filter, .partition, .remp] { nil_value() } else { first } } if kind in [.filter, .partition, .remp] { state.remaining = first.list_length()! } } m.env.slots[4] = payload_value(.list_utility, state) for i in 0 .. 4 { m.env.slots[i] = unspecified() } } @[direct_array_access] fn (mut m Machine) step_list_utility(mut vm VM) ! { mut state := list_utility_state(m.env.slots[4]) if state.kind == .fold_right { if state.remaining == 0 { m.finish_call(state.accumulator) return } m.push(state.callback) row := (state.remaining - 1) * state.inputs for i in 0 .. state.inputs { m.push(state.rows[row + i]) } m.push(state.accumulator) m.apply(mut vm, state.inputs + 1, false)! return } if state.kind in [.for_all, .exists, .fold_left] { mut empty := 0 mut last := true for cursor in state.cursors { if cursor.value.tag == .nil { empty++ continue } if cursor.value.tag != .pair { return failure('expected a proper list') } last = last && cursor.value.pair_pointer().cdr.tag == .nil } if empty > 0 { if empty != state.inputs { return failure('list inputs must have equal lengths') } m.finish_call(if state.kind == .fold_left { state.accumulator } else { boolean(state.kind == .for_all) }) return } m.push(state.callback) if state.kind == .fold_left { m.push(state.accumulator) } for cursor in state.cursors { m.push(cursor.value.pair_pointer().car) } // The report explicitly requires a proper tail call on the final row. m.apply(mut vm, state.inputs + int(state.kind == .fold_left), last && state.kind != .fold_left)! return } short := state.kind in [.find, .memp, .assp] if (short && state.cursor.value.tag == .nil) || (!short && state.remaining == 0) { if short { m.finish_call(boolean(false)) } else { selected := state.list_utility_result(false) if state.kind == .partition { m.finish_call(payload_value(.multiple, &Vector{ items: [selected, state.list_utility_result(true)] })) } else { m.finish_call(selected) } } return } if state.cursor.value.tag != .pair { return failure('expected a proper list') } item := state.cursor.value.pair_pointer().car state.pending = item candidate := if state.kind == .assp { head, _ := item.pair_parts()! head } else { item } m.push(state.callback) m.push(candidate) m.apply(mut vm, 1, false)! } @[direct_array_access] fn (mut m Machine) collect_list_utility() ! { result := m.pop_value() if result.tag == .multiple { return failure('list callback must return one value') } mut state := list_utility_state(m.env.slots[4]) if state.kind in [.find, .memp, .assp] && result.is_true() { m.finish_call(if state.kind == .memp { state.cursor.value } else { state.pending }) return } if state.kind == .for_all && !result.is_true() { m.finish_call(boolean(false)) return } if state.kind == .exists && result.is_true() { m.finish_call(result) return } if m.env.escaped { mut scope := m.detach_bridge() state = &ListUtilityState{ ...state, persistent: true, cursors: state.cursors.clone() } scope.slots[4] = payload_value(.list_utility, state) } state.steps++ match state.kind { .fold_right { state.accumulator = result state.remaining-- } .fold_left { state.accumulator = result for mut cursor in state.cursors { cursor.advance(false, state.steps)! } state.remaining-- } .for_all, .exists { for mut cursor in state.cursors { cursor.advance(true, state.steps)! } } .filter, .partition, .remp { keep := if state.kind == .remp { !result.is_true() } else { result.is_true() } if keep || state.kind == .partition { state.append_list_utility(state.pending, !keep) } state.cursor.advance(false, state.steps)! state.remaining-- } else { state.cursor.advance(true, state.steps)! } } state.pending = unspecified() } fn (mut state ListUtilityState) append_list_utility(value Value, rejected bool) { if state.persistent { if rejected { state.rejected_suffix = cons(value, state.rejected_suffix) } else { state.selected_suffix = cons(value, state.selected_suffix) } return } node := &Pair{ car: value, cdr: nil_value() } link := payload_value(.pair, node) if rejected { if isnil(state.rejected_tail) { state.rejected = link } else { state.rejected_tail.cdr = link } state.rejected_tail = node } else { if isnil(state.selected_tail) { state.selected = link } else { state.selected_tail.cdr = link } state.selected_tail = node } } fn (state &ListUtilityState) list_utility_result(rejected bool) Value { prefix := if rejected { state.rejected } else { state.selected } if !state.persistent { return prefix } mut suffix := if rejected { state.rejected_suffix } else { state.selected_suffix } mut ordered := nil_value() for suffix.tag == .pair { pair := suffix.pair_pointer() ordered = cons(pair.car, ordered) suffix = pair.cdr } mut out := ListBuilder{} mut cursor := prefix for cursor.tag == .pair { pair := cursor.pair_pointer() out.push(pair.car) cursor = pair.cdr } return out.finish(ordered) } fn utility_cons_star(mut _vm VM, args []Value) !Value { check_arity('cons*', args.len, 1, -1)! mut result := args.last() for i := args.len - 2; i >= 0; i-- { result = cons(args[i], result) } return result } fn utility_remove(mut _vm VM, args []Value) !Value { return utility_remove_matching(args, 'remove', true) } fn utility_remv(mut _vm VM, args []Value) !Value { return utility_remove_matching(args, 'remv', false) } fn utility_remq(mut _vm VM, args []Value) !Value { return utility_remove_matching(args, 'remq', false) } fn utility_remove_matching(args []Value, name string, structural bool) !Value { check_arity(name, args.len, 2, 2)! length := args[1].list_length()! mut cursor := args[1] mut output := ListBuilder{} for _ in 0 .. length { pair := cursor.pair_pointer() matches := if structural { equal(args[0], pair.car) } else { eqv(args[0], pair.car) } if !matches { output.push(pair.car) } cursor = pair.cdr } return output.finish(nil_value()) }