|
| 1 | +// Copyright 2025 International Digital Economy Academy |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +///| |
| 16 | +pub enum L { |
| 17 | + Nil |
| 18 | + Cons(Int, mut tail~ : L) |
| 19 | +} derive(Eq, Show) |
| 20 | + |
| 21 | +///| |
| 22 | +/// tail recursive map using dps |
| 23 | +pub fn map(self : L, f : (Int) -> Int) -> L { |
| 24 | + match self { |
| 25 | + Nil => Nil |
| 26 | + Cons(head, tail~) => { |
| 27 | + let cell = Cons(f(head), tail=Nil) |
| 28 | + map_dps(f, tail, cell) |
| 29 | + cell |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +///| |
| 35 | +fn map_dps(f : (Int) -> Int, lst : L, dest : L) -> Unit { |
| 36 | + loop lst, dest { |
| 37 | + Nil, Cons(_, ..) as c => c.tail = Nil |
| 38 | + // c.tail = lst |
| 39 | + // this is a common error |
| 40 | + Cons(head, tail~), Cons(_, ..) as c => { |
| 41 | + let cell = Cons(f(head), tail=Nil) |
| 42 | + c.tail = cell |
| 43 | + continue tail, cell |
| 44 | + } |
| 45 | + _, Nil => abort("map_dps: dest is Nil") |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +test "map" { |
| 50 | + let lstL : L = Cons( |
| 51 | + 1, |
| 52 | + tail=Cons(2, tail=Cons(3, tail=Cons(4, tail=Cons(5, tail=Nil)))), |
| 53 | + ) |
| 54 | + let lst : L = map(lstL, fn { x => x * 2 }) |
| 55 | + inspect!( |
| 56 | + lst, |
| 57 | + content="Cons(2, tail=Cons(4, tail=Cons(6, tail=Cons(8, tail=Cons(10, tail=Nil)))))", |
| 58 | + ) |
| 59 | +} |
0 commit comments