File: catlist.sml

package info (click to toggle)
mlton 20210117%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 58,464 kB
  • sloc: ansic: 27,682; sh: 4,455; asm: 3,569; lisp: 2,879; makefile: 2,347; perl: 1,169; python: 191; pascal: 68; javascript: 7
file content (76 lines) | stat: -rw-r--r-- 1,825 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
(*
 * Constant time concatenable list.  
 *
 * -- Allen
 *)

signature CATNETABLE_LIST =
sig
   type 'a catlist 
   val empty    : 'a catlist
   val null     : 'a catlist -> bool
   val length   : 'a catlist -> int
   val cons     : 'a * 'a catlist -> 'a catlist
   val unit     : 'a -> 'a catlist
   val append   : 'a catlist * 'a catlist -> 'a catlist
   val hd       : 'a catlist -> 'a
   val tl       : 'a catlist -> 'a catlist

   val fromList : 'a list -> 'a catlist
   val toList   : 'a catlist -> 'a list

   val map   : ('a -> 'b) -> 'a catlist -> 'b catlist
   val app   : ('a -> unit) -> 'a catlist -> unit
end

structure CatnetableList :> CATNETABLE_LIST =
struct
    datatype 'a catlist = empty | unit of 'a | @ of 'a catlist * 'a catlist

    fun null empty = true
      | null _     = false

    fun length empty    = 0
      | length (unit _) = 1
      | length (a @ b)  = length a + length b 

    fun hd empty    = raise Empty
      | hd (unit a) = a
      | hd (a @ b)  = hd a

    fun tl empty          = raise Empty
      | tl (unit a)       = empty
      | tl ((unit _) @ a) = a
      | tl ((a @ b) @ c)  = tl(a @ (b @ c))
      | tl (empty @ c)    = tl c

    fun cons(a,empty) = unit a
      | cons(a,b)     = unit a @ b

    fun append(empty,a) = a
      | append(a,empty) = a
      | append(a,b)     = a @ b

    fun map f l = 
    let fun g empty    = empty
          | g (unit a) = unit(f a)
          | g (a @ b)  = (g a) @ (g b)
    in  g l end

    fun app f l =
    let fun g empty    = ()
          | g (unit a) = f a
          | g (a @ b)  = (g a; g b)
    in  g l end

    fun fromList []     = empty
      | fromList (a::b) = cons(a,fromList b)

    fun toList l = 
    let fun g(empty,l)  = l
          | g(unit a,l) = a::l
          | g(a @ b, l) = g(a,g(b,l))
    in  g(l,[]) end

end