Skip to content

Instantly share code, notes, and snippets.

@echeran
Created March 23, 2018 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save echeran/ac92b0603b5e7741e49cc86ce7dca0fe to your computer and use it in GitHub Desktop.
Save echeran/ac92b0603b5e7741e49cc86ce7dca0fe to your computer and use it in GitHub Desktop.
/*
Copyright 2018 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
object LangUtil
{
/**
* Given two operands that are the same concrete Option type, and a binary
* function, return the result of the operation as an option in a default
* way.
*
* @param val1
* @param val2
* @param op
* @tparam U
* @tparam V
* @return
*/
def optionGenericOp[U,V](val1: Option[U], val2: Option[U], op: (U,U) => V): Option[V] = {
(val1, val2) match {
case (Some(a), Some(b)) => Option(op(a, b))
case (None, None) => None
case (_, None) => None
case (None, _) => None
case _ => None // redundant
}
}
/**
* Provide the logical equivalent of && for Option[Boolean]
*
* @param b1
*/
def optionAnd(b1: Option[Boolean], b2: Option[Boolean]): Option[Boolean] = {
optionGenericOp(b1, b2, (x: Boolean, y: Boolean) => x && y)
}
/**
* Provide the logical equivalent of || for Option[Boolean]
* @param b1
* @param b2
* @return
*/
def optionOr(b1: Option[Boolean], b2: Option[Boolean]): Option[Boolean] = {
optionGenericOp(b1, b2, (x: Boolean, y: Boolean) => x || y)
}
//
// pretty-printing util fns
//
def prettyPrintableMap[K,V](m: Map[K,V]): String = {
val keys = m.keys.toSeq
val kvLines = keys.map(k => s"\t$k -> \t${m(k)}")
kvLines.mkString("\n")
}
def prettyPrintableSortableMap[K,V,B](m: Map[K,V], keySortBy: K => B)(implicit ord: math.Ordering[B]): String = {
val keys = m.keys.toSeq.sortBy(keySortBy)
val kvLines = keys.map(k => s"\t$k -> \t${m(k)}")
kvLines.mkString("\n")
}
def prettyPrintableSortableMap[K <: Ordered[K],V](m: Map[K,V]): String = {
val keys = m.keys.toSeq.sorted
val kvLines = keys.map(k => s"\t$k -> \t${m(k)}")
kvLines.mkString("\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment