juan_gandhi: (Default)
2019-03-27 06:36 pm
Entry tags:

kind of improvement

Just figured out how to calculate elements of yx for two sets (passed here as lists)

An element of an exponential is a Map[X, Y].

  /**
    * Set of all possible maps from set xs to set ys
    * @param xs domain of maps
    * @param ys codomain of maps
    * @tparam X type of domain elements
    * @tparam Y type of codomain elements
    * @return the set of all possible maps
    */
  def exponent[X, Y](xs: Set[X], ys: Set[Y]): Set[Map[X, Y]] = {
    setOf(allMaps(xs.toList, ys.toList),
      pow(ys size, xs size),
      (m: Map[X, Y]) => xs == m.keySet
    )
  }

  def allMaps[X, Y](xs: List[X], ys: List[Y]): List[Map[X, Y]] =
    (List(Map.empty[X, Y]) /: xs)((maps, x) =>
      maps flatMap (m => ys map (y => m + (x -> y)))
    )
juan_gandhi: (Default)
2019-03-24 07:32 pm
Entry tags:

learned something

if your class is not a function of its constructor parameters (like, e.g., case class is), don't introduce these parameters at all. Make them members. Use a factory to build your class.

Then you can turn them into traits, and compose them freely. That's just one advantage.

The other advantage is that you won't need to reassign parameter values to members that are already declared in traits.

In short, careful with constructors. You may not need them. Scala is not C++, you know. 

juan_gandhi: (Default)
2019-03-20 04:10 pm
Entry tags:

literary coding







  
  implicit class Optimist[T](opt: Result[T]) {
    def iHope: T = opt.fold(
      identity,
      errors => throw new InstantiationException(errors.mkString(";")))
   }



use case:

  def asCat(source: Category): Cat = convert2Cat(source)(_.toString, _.toString) iHope
 
juan_gandhi: (Default)
2019-03-09 12:07 pm
Entry tags:

три-четыре способа перевернуть список

Вот тут код, по линку кликайте 

1) рекурсивный

2) Тони Моррис, flip/cons

3) "скальная версия" [personal profile] snowps 

 4) то же самое, но практичная версия, с массивом


Running 70000 elements
Recursively: 9 ms
FlipCons: 25 ms
Snowps: 12894 ms
Snowps with array: 5 ms

Конечно, не особо честно, jvm надо было сначала прогреть как следует.

Это я нашел какую-то хрень неведомой древности.
juan_gandhi: (Default)
2019-03-02 05:32 pm
Entry tags:

scala, scala...






  lazy val ParallelPair = category"({0, 1}, {a:0->1, b:0->1})"
juan_gandhi: (Default)
2019-02-25 08:09 pm
Entry tags:

Scala bashing

1. If in your trait MyTrait you have val x: String = "This is my string", and refer this x from something that extends MyTrait, you can easily get AbstractMethodError during runtime. If you make it lazy val x..., it'll work. If you make it def x..., it'll work even better.

2. Similar things may happen if you extend a trait e.g. trait MyTrait[C] { val dom: C; def op(x: dom.X): String} and have
class Z[D] extends MyTrait[D] { 
  override def op(x: dom.X): String { println("hi") }
  def doit(z: dom.X) = { op(x)  }
}


and then have val sample = new Z[Int](){ override def op(x: dom.X): String { println("wow") }},
and then call sample.doit(42), you can have either AbstractMethodException or have the op called that is not defined in your instance.

3. The argument type of MyTrait.op(dom.X) is, according to reflection, is java.lang.Object.

The latter is kind of obvious, since, well, what is it. But it makes everything just fake.

And I wonder, is it Scala, is it JVM, or is it Curry Type System?

Fuck, in short.
juan_gandhi: (Default)
2019-02-24 05:04 pm
Entry tags:

wtf with type name

I have a class named `Category`, and it has a member `type Object`, so far so good.
But then in one place the compiled code (or JVM) does not understand that it is not `java.lang.Object`, and tries to find a method that takes `java.lang.Object` while the methods I have takes some path-dependent type named `Object`.

So, to avoid this stupidity with JVM (or scala compiler), I have to find an alternative name. Can't figure out what it can be. Just `O` (and `A` for arrows?)

I'm in panic.

juan_gandhi: (Default)
2019-02-13 06:50 am
Entry tags:

HttpStatusCode

Решил я использовать этот тип в качестве индикатора состояния при ответе (примерно имея в виду, что мы тут нынче все притворяемся вебсервисами). Ну как бы сделать вариант Result, назвать WSResult. На скале. Но не хотел зависеть от акки.
Пошел смотреть, че там у джавы. Апачи я брезгую (да там то же самое), а в джаве? А там просто список целых чисел, с названиями. И не все ответы, что перечислены в RFE, в джаве имеются в наличии.

Не, ну я так не играю. Кто там говорил, что "джава улучшается"? Такие же уебки, да еще теперь они все в Оракле, кто не успел убежать.

Придется с аккой. В принципе-то, это отдельная тема, RichResponse[T](httpCode, content: Option[T]).

juan_gandhi: (Default)
2019-01-22 05:52 am
Entry tags:

equality tricks

Category theory is not equational. Meaning, in category theory equality is not defined for objects. We can only state that two objects are isomorphic. Well, of course x == x, but that's it; we can't always know whether x == y or not.

Now, to check for an isomorphism, we need to verify whether f ∘ g == id and g ∘ f == id. So we need some kind of equality for arrows. But if we could compare idx and idy, it would mean we could check whether x == y or not. No such thing is generally available. Yes, f == g implies dom(f) == dom(g) and codom(f) == codom(g) - but this is not available, so two different arrows are not comparable either.

Comparability is only local, that is, given x and y, and a couple of arrows, f: x → y and g: x → y, we can check whether f == g or not - but not in general settings.

This is okay. Except that, imagine, you define categories as (directed) (multi-)graphs with composition and identities. In this case we somehow have to discard equality of graph nodes. This is weird. A graph theory is usually considered to be equational. A non-equational graph theory is something one has to deal with if graphs are taken as a supertheory for category theory.

Why does not it bother me. I am implementing categories (as graphs) in Scala. And since Scala is a Curry type language (that is, with subtyping), comparing, e.g. two graphs (or two categories) is probably not implementable without using .asInstanceOf. So, a prudent programmer has two choices: either use .asInstanceOf - like Scala library does for sets (with a rather obvious error), or totally discard equationality for graph nodes. And this is unusual. E.g. we won't be able to produce a set of graphs. Or a set of objects of a category. Kind of challenging. Kind of new.
juan_gandhi: (Default)
2019-01-21 07:40 pm
Entry tags:

ok, it does not seem to be doable

Basically, I have two, e.g. GraphMorphisms, and I want to compare them. This theory is supposed to be equational, right? Is it?
In short, I could not figure out.

So I decide, let me take a look, how do they compare two typed sets in Scala? Here's how:

  override def equals(that: Any): Boolean = that match {
    case that: GenSet[_] =>
      (this eq that) ||
      (that canEqual this) &&
      (this.size == that.size) &&
      (try this subsetOf that.asInstanceOf[GenSet[A]]
       catch { case ex: ClassCastException => false })
    case _ =>
      false
  }


So there. Maybe it's not equational, after all. I mean, in my case.

How do they do it in Haskell then? This is how:


instance Eq1 Set where
    liftEq eq m n =
        size m == size n && liftEq eq (toList m) (toList n)


Typeclasses seem to beat classes. Fuck...
juan_gandhi: (Default)
2018-12-21 12:52 am
Entry tags:

вот еще была 10-я скала

scala> def sample: Set[Any] = Set(1.0, 2.0, Double.NaN)
sample: Set[Any]

scala> val sample1 = sample; val sample2 = sample
sample1: Set[Any] = Set(1.0, 2.0, NaN)
sample2: Set[Any] = Set(1.0, 2.0, NaN)

scala> import collection.JavaConverters._
import collection.JavaConverters._

scala> sample2.asJava.asScala == sample1
res21: Boolean = false

scala> sample1 == sample2.asJava.asScala
res22: Boolean = true


Не берите в голову, в 12-й это все "пофиксено".
juan_gandhi: (Default)
2018-12-20 01:22 am
Entry tags:

unnatural transformation

scala> def f(x: AnyRef) = System.identityHashCode(x)
f: (x: AnyRef)Int

scala> def s = Set("a", "bc", "def")
s: scala.collection.immutable.Set[String]

scala> val list = List(s, s)
list: List[scala.collection.immutable.Set[String]] = List(Set(a, bc, def), Set(a, bc, def))

scala> val s1 = list.map(f).toSet
s1: scala.collection.immutable.Set[Int] = Set(508760925, 1987354705)

scala> val s2 = list.toSet.map(f)
s2: scala.collection.immutable.Set[Int] = Set(508760925)

juan_gandhi: (Default)
2018-12-20 01:18 am
Entry tags:

set that is not

Update. Это была 10-я скала.

scala> def sample: Set[Any] = Set(1.0, 2.0, Double.NaN)
sample: Set[Any]

scala> val sample1 = sample; val sample2 = sample
sample1: Set[Any] = Set(1.0, 2.0, NaN)
sample2: Set[Any] = Set(1.0, 2.0, NaN)

scala> sample1 == sample2
res1: Boolean = false
juan_gandhi: (Default)
2018-12-10 07:34 pm
Entry tags:

something not very expected

scala> val y = if ("1" == "2") "yes"
y: Any = ()

juan_gandhi: (Default)
2018-12-02 09:49 am
Entry tags:

btw, some code I found

  val x = someFunction(args) 
  val goodX = Try(x).toOption.flatMap(Option(_))



The explanation was - "this way we avoid having Some(null)".
juan_gandhi: (Default)
2018-11-24 05:06 pm
Entry tags:

thinking whether I need a test for this trait

 package math.cat

import scala.reflect.ClassTag

trait NonEnumerableSet[T] extends Set[T] {
private def notEnumerable =
throw new UnsupportedOperationException("This set is not enumerable")

override def isEmpty: Boolean = notEnumerable

def iterator: Iterator[T] = notEnumerable

override def toArray[S >: T : ClassTag]: Array[S] = notEnumerable

override def +(elem: T): Set[T] = notEnumerable

override def -(elem: T): Set[T] = notEnumerable

}
juan_gandhi: (Default)
2018-11-22 01:19 pm

а хрен ли радоваться...

...что много рабочих мест для функциональщиков и скальщиков... это, очевидно, означает, что зарплаты не такие уж замечательные прелдлагают. Хорошие программисты нужны, а вот только денег пока нет (но вы держитесь).

 
juan_gandhi: (Default)
2018-11-22 09:13 am
Entry tags:

an important reading

http://days2012.scala-lang.org/sites/days2012/files/bjarnason_trampolines.pdf

Also, it's a shame, but I never heard of java.util.control things like TailCalls. How come, I don't know. Have to learn some Scala, eh.