fun mem [] a = false
| mem (x::xs) a = a=x orelse mem xs a

fun remdupl [] = []
| remdupl [x] = [x]
| remdupl (x::xs) = if mem xs x
then remdupl xs
else x::(remdupl xs)

fun rm a [] = []
| rm a (x::xs) = if a=x
then xs
else x::(rm a xs)

fun rmall a [] = []
| rmall a (x::xs) = if a=x
then rmall a xs
else x::(rmall a xs)

fun contains _ [] = true
| contains [] (x::xs) = false
| contains ys (x::xs) = (mem ys x) andalso (contains ys xs)

fun contains_all _ [] = true
| contains_all [] (x::xs) = false
| contains_all ys (x::xs) =
(mem ys x) andalso (contains_all (rm x ys) xs)

fun intersect [] ys = []
| intersect xs [] = []
| intersect (x::xs) ys =
if mem ys x
then x::(intersect xs (rm x ys))
else intersect xs ys

fun union l1 l2 = l1^^l2

fun listsub xs [] = xs
| listsub [] _ = raise Subtract
| listsub xs (y::ys) =
if mem xs y
then listsub (rm y xs) ys
else raise Subtract

fun ins l x = l^^[x]

fun ins_new l x =
if mem l x
then l
else ins l x

Examples using list functions

The examples below use lists of integers, but the functions can be used for lists of elements of any type, e.g. lists of strings, lists of boolean values, lists of records from record color sets, etc.

mem [1,2,3] 2 (* returns true *)
mem [1,2,3] 4 (* returns false *)

remdupl [1,2,3,2,4,2,5,3] (* returns [1,4,2,5,3] *)
remdupl [1,2,3] (* returns [1,2,3] *)

rm 3 [1,2,3,4,3,5] (* returns [1,2,4,3,5] *)
rm 3 [1,2,4,5] (* returns [1,2,4,5] *)

rmall 3 [1,2,3,4,3,5] (* returns [1,2,4,5] *)

contains [1,2,3] [3,2] (* returns true *)
contains [1,2,3] [3,2,3] (* returns true *)
contains [1,2,3] [3,4,2] (* returns false *)

contains_all [1,2,3] [3,2] (* returns true *)
contains_all [1,2,3] [3,2,3] (* returns false *)
contains_all [1,2,3] [3,4,2] (* returns false *)

intersect [1,2,3] [2,3,4] (* returns [2,3] *)
intersect [1,2,3,2] [2,3,4] (* returns [2,3] *)
intersect [] [1,2,3] (* returns [] *)

listsub [1,2,3,2] [1,2] (* returns [3,2] *)
listsub [1,2,3] [1,2,2] (* exception Subtract is raised *)

ins [1,2,3] 2 (* returns [1,2,3,2] *)

ins_new [1,2,3] 4 (* returns [1,2,3,4] *)
ins_new [1,2,3] 2 (* returns [1,2,3] *)

sort INT.lt [3,1,4,2,5,4] (* returns [1,2,3,4,4,5] *)

Related pages

List color sets

String color sets
Enumerated color sets

You must be logged in to post a comment.