Skip to content

Commit

Permalink
Added simple Bijection type
Browse files Browse the repository at this point in the history
  • Loading branch information
propensive committed Oct 5, 2024
1 parent f449110 commit 3e01ab1
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/core/rudiments-core.scala
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ extension [ElemType](array: Array[ElemType])

extension [KeyType, ValueType](map: sc.Map[KeyType, ValueType])
inline def has(key: KeyType): Boolean = map.contains(key)
inline def bijection: Bijection[KeyType, ValueType] = Bijection(map.to(Map))

extension [KeyType, ValueType](map: Map[KeyType, ValueType])
def upsert(key: KeyType, op: Optional[ValueType] => ValueType): Map[KeyType, ValueType] =
Expand Down
24 changes: 24 additions & 0 deletions src/core/rudiments.Bijection.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package rudiments

import scala.collection as sc

object Bijection:
def apply[KeyType, ValueType](map: Map[KeyType, ValueType]): Bijection[KeyType, ValueType] =
Bijection(map, map.map(_.swap).to(Map))

case class Bijection[KeyType, ValueType]
(map: Map[KeyType, ValueType], transposition: Map[ValueType, KeyType])
extends Iterable[(KeyType, ValueType)], sc.Map[KeyType, ValueType]:
private inline def bijection: this.type = this
def iterator: Iterator[(KeyType, ValueType)] = map.iterator

infix def - (key: KeyType): Bijection[KeyType, ValueType] =
Bijection(map - key, transposition - map(key))

infix def - (key1: KeyType, key2: KeyType, keys: Seq[KeyType]): Bijection[KeyType, ValueType] =
Bijection(map - key1 - key2 -- keys, transposition - map(key1) - map(key2) -- keys.map(map(_)))

def get(key: KeyType): Option[ValueType] = map.get(key)
def flip: Bijection[ValueType, KeyType] = new Bijection(transposition, map):
override def flip: Bijection[KeyType, ValueType] = bijection

10 changes: 10 additions & 0 deletions src/core/rudiments.Indexable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ object Indexable:
def contains(value: Self, index: KeyType): Boolean = value.contains(index)
def access(value: Self, index: KeyType): ValueType = value(index)

given [KeyType, ValueType]
=> Bijection[KeyType, ValueType] is Indexable by KeyType into ValueType as bijection =
new Indexable:
type Self = Bijection[KeyType, ValueType]
type Operand = KeyType
type Result = ValueType

def contains(value: Self, index: KeyType): Boolean = value.map.contains(index)
def access(value: Self, index: KeyType): ValueType = value.map(index)

given [KeyType, ValueType]
=> scm.HashMap[KeyType, ValueType] is Indexable by KeyType into ValueType as hashMap =

Expand Down

0 comments on commit 3e01ab1

Please sign in to comment.