Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Last active December 15, 2017 03:44
Show Gist options
  • Save izmailoff/fe1f99d4265edbc1096ee42badeabad7 to your computer and use it in GitHub Desktop.
Save izmailoff/fe1f99d4265edbc1096ee42badeabad7 to your computer and use it in GitHub Desktop.
Example of functional sets in Scala
type Set = Int => Boolean
val setOf_1: Set = (i: Int) => (i == 1)
val empty: Set = (i: Int) => false
val union: (Set, Set) => Set =
(s1: Set, s2: Set) => (i: Int) => s1(i) || s2(i)
val intersect: (Set, Set) => Set =
(s1: Set, s2: Set) => (i: Int) => s1(i) && s2(i)
val setOf_5_3_2 = union(union(_ == 5, _ == 3), _ == 2)
setOf_5_3_2(5)
setOf_5_3_2(2)
setOf_5_3_2(1)
val setOf_5_3_2_1 = union(setOf_1, setOf_5_3_2)
setOf_5_3_2_1(3)
setOf_5_3_2_1(1)
@izmailoff
Copy link
Author

izmailoff commented Oct 28, 2016

Output from running the above code in REPL:

scala> type Set = Int => Boolean
defined type alias Set


scala> val setOf_1: Set = (i: Int) => (i == 1)
setOf_1: Set = <function1>


scala> val empty: Set = (i: Int) => false
empty: Set = <function1>


scala> val union: (Set, Set) => Set =
     |   (s1: Set, s2: Set) => (i: Int) => s1(i) || s2(i)
union: (Set, Set) => Set = <function2>


scala> val intersect: (Set, Set) => Set =
     |   (s1: Set, s2: Set) => (i: Int) => s1(i) && s2(i)
intersect: (Set, Set) => Set = <function2>


scala> val setOf_5_3_2 = union(union(_ == 5, _ == 3), _ == 2)
setOf_5_3_2: Set = <function1>


scala> setOf_5_3_2(5)
res0: Boolean = true


scala> setOf_5_3_2(2)
res1: Boolean = true


scala> setOf_5_3_2(1)
res2: Boolean = false


scala> val setOf_5_3_2_1 = union(setOf_1, setOf_5_3_2)
setOf_5_3_2_1: Set = <function1>


scala> setOf_5_3_2_1(3)
res3: Boolean = true


scala> setOf_5_3_2_1(1)
res4: Boolean = true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment