Singly-linked list/Element insertion: Difference between revisions

Line 649:
 
I repeated the ‘Rosetta Code linear list type’ here, so you can simply copy
thethis code, compile it, and run it.
 
Also I put the executable parts in initialization rather than the main program,
to avoid being forced to finalize‘consume’ the list (free its memory). I felt that would be a distraction.
 
Notice that the insertion routine proves that the resulting list is either of
Line 667:
| {0 <= n} rclist_vt_cons (vt, n + 1) of (vt, rclist_vt (vt, n))
 
(* AnA axiomlemma one will need: lists never have negative lengths. *)
extern praxiprfun {vt : vt@ype}
lemma_rclist_vt_param
rclist_vt_param {n : int}
(lst{n : !rclist_vt (vt, n)) :<prf>int}
(lst : !rclist_vt (vt, n)) :<prf> [0 <= n] void
 
(* Proof of the lemma. *)
primplement {vt}
lemma_rclist_vt_param lst =
case+ lst of
| rclist_vt_nil () => ()
| rclist_vt_cons _ => ()
 
(*------------------------------------------------------------------*)
Line 728 ⟶ 735:
(* The following is needed to prove that the initial k above
satisfies 0 <= k. *)
prval _ = rclist_vt_paramlemma_rclist_vt_param lst
 
val _ = find (lst, after, x)
Line 734 ⟶ 741:
 
(* Now let’s try it. *)
 
(* Some convenient notation. *)
#define NIL rclist_vt_nil ()
#define :: rclist_vt_cons
overload insert with rclist_int_insert
 
val A = 123
val B = 789
Line 740 ⟶ 753:
(* ‘var’ to make lst a mutable variable rather than a
value (‘val’). *)
var lst = rclist_vt_cons (A, rclist_vt_cons:: (B, rclist_vt_nil:: ()))NIL
 
(* Do the insertion. *)
val () = rclist_int_insertinsert (lst, A, C)
 
fun
Line 749 ⟶ 762:
(p : !rclist_vt (int, k)) : void =
case+ p of
| rclist_vt_nil ()NIL => ()
| rclist_vt_cons (head, :: tail) =>
begin
println! (head);
loop tail
end
prval () = rclist_vt_paramlemma_rclist_vt_param lst
val () = loop lst
 
Line 764 ⟶ 777:
 
{{out}}
<pre>$ patscc -DATS_MEMALLOC_LIBC singly_linked_listsingly_linked_list_insertion.dats && ./a.out
123
456
1,448

edits