src/Pure/General/same.ML
author wenzelm
Thu Jul 16 21:28:39 2009 +0200 (2009-07-16 ago)
changeset 32022 c2f4ee07647f
parent 32017 e91a3acf8383
child 32025 e8fbfa84c23f
permissions -rw-r--r--
added map_option;
wenzelm@32015
     1
(*  Title:      Pure/General/same.ML
wenzelm@32015
     2
    Author:     Makarius
wenzelm@32015
     3
wenzelm@32015
     4
Support for copy-avoiding functions on pure values, at the cost of
wenzelm@32015
     5
readability.
wenzelm@32015
     6
*)
wenzelm@32015
     7
wenzelm@32015
     8
signature SAME =
wenzelm@32015
     9
sig
wenzelm@32015
    10
  exception SAME
wenzelm@32015
    11
  type ('a, 'b) function = 'a -> 'b  (*exception SAME*)
wenzelm@32015
    12
  type 'a operation = ('a, 'a) function  (*exception SAME*)
wenzelm@32015
    13
  val commit: 'a operation -> 'a -> 'a
wenzelm@32015
    14
  val function: ('a -> 'b option) -> ('a, 'b) function
wenzelm@32015
    15
  val capture: ('a, 'b) function -> 'a -> 'b option
wenzelm@32017
    16
  val map: 'a operation -> 'a list operation
wenzelm@32022
    17
  val map_option: ('a, 'b) function -> ('a option, 'b option) function
wenzelm@32015
    18
end;
wenzelm@32015
    19
wenzelm@32015
    20
structure Same: SAME =
wenzelm@32015
    21
struct
wenzelm@32015
    22
wenzelm@32015
    23
exception SAME;
wenzelm@32015
    24
wenzelm@32015
    25
type ('a, 'b) function = 'a -> 'b;
wenzelm@32015
    26
type 'a operation = ('a, 'a) function;
wenzelm@32015
    27
wenzelm@32015
    28
fun commit f x = f x handle SAME => x;
wenzelm@32015
    29
wenzelm@32015
    30
fun capture f x = SOME (f x) handle SAME => NONE;
wenzelm@32015
    31
wenzelm@32015
    32
fun function f x =
wenzelm@32015
    33
  (case f x of
wenzelm@32015
    34
    NONE => raise SAME
wenzelm@32015
    35
  | SOME y => y);
wenzelm@32015
    36
wenzelm@32017
    37
fun map f [] = raise SAME
wenzelm@32017
    38
  | map f (x :: xs) = (f x :: commit (map f) xs handle SAME => x :: map f xs);
wenzelm@32015
    39
wenzelm@32022
    40
fun map_option f NONE = raise SAME
wenzelm@32022
    41
  | map_option f (SOME x) = SOME (f x);
wenzelm@32022
    42
wenzelm@32015
    43
end;