Skip to content

Instantly share code, notes, and snippets.

@p-pavel
Last active October 8, 2024 22:46
Show Gist options
  • Save p-pavel/48368dc107fbbdc3502907ffc873ea42 to your computer and use it in GitHub Desktop.
Save p-pavel/48368dc107fbbdc3502907ffc873ea42 to your computer and use it in GitHub Desktop.
MeetSemilattice for longest string prefix
//> using scala 3.5.1
//> using options -Wunused:all -deprecation -Xkind-projector -rewrite -source future-migration
//> using dep org.typelevel::algebra:2.12.0
//> using test.dep org.typelevel::discipline-munit:2.0.0
//> using test.dep org.typelevel::algebra-laws:2.12.0
import algebra.laws.LatticeLaws
import algebra.lattice.MeetSemilattice
given MeetSemilattice[String] with
/** @todo use for DirectedSet */
def zero: String = ""
extension (s1: String) def longestPrefixWith(s2: String) =
val shortest = if s1.size < s2.size then s1 else s2
val maxPrefixLen = shortest.indices.find(i => s1(i) != s2(i))
maxPrefixLen.map(shortest.take).getOrElse(shortest)
final override def meet(lhs: String, rhs: String): String = lhs.longestPrefixWith(rhs)
end given
/** Algebraically this is bounded join semilattice (or distributive lattice)
* @see
* https://en.wikipedia.org/wiki/Semilattice
* @see
* https://typelevel.org/cats/algebra.html
* @todo
* TODO: consider interpreting it as a DirectedSet
*/
class LongestPrefixLaws extends munit.DisciplineSuite:
checkAll("Longest prefix", LatticeLaws[String].meetSemilattice)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment