FAQ Database Discussion Community


Covariant Trees in Scala

scala,data-structures,tree,scalaz
Looking at scalaz.Tree[A], it is invariant in A. I'm looking for a multi-way tree which I can dump values of a hierarchy in E.g. if I have an ADT of trait MyThing case object Thing1 extends MyThing case object Thing2 extends MyThing And I want a Tree of MyThings, I...

Returning NonEmptyList `sealed trait`'s w/ scalaz.Validation

scala,scalaz,applicative
Given the following code: object Person { override def makePerson(name: String, age: Int, gender: Gender): Validation[NonEmptyList[InvalidPersonError], Person] = (validateName(name) |@| validateAge(age)) {_ ++ _} private def validateName(name: String): Validation[NonEmptyList[InvalidPersonError], String] = if(name.nonEmpty) name.successNel else InvalidName.failureNel private def validateAge(age: Int): Validation[NonEmptyList[InvalidPersonError], Int] = if(age >= 0) age.successNel else InvalidAge.failureNel sealed trait...

JDBC Insert with Postgres Enum

sql,scala,scalaz
Given the following Person SQL and model code: SQL CREATE TYPE sex AS ENUM ('male', 'female'); CREATE TABLE person ( id bigserial primary key, name varchar(100) NOT NULL, age integer NOT NULL, gender sex NOT NULL ); Code object Person { sealed trait Gender case object Male extends Gender case...

How to compose functions that return Validation?

scala,validation,scalaz,applicative
This is a follow-up to my previous question Suppose I have two validating functions that return either the input if it is valid or the error messages if it is not. type Status[A] = ValidationNel[String, A] val isPositive: Int => Status[Int] = x => if (x > 0) x.success else...

Filtering values on right side of scalaz disjunction

scala,scalaz
I have a result consisting of a list of Vectors in a scalaz disjunction and I want to be able to examine and filter out elements from within the right side. simplified example: import scalaz._ import Scalaz._ type TL = Throwable \/ List[Vector[Int]] val goodTL: TL = \/-(List(Vector(1,2,3),Vector(), Vector(2,3,4))) If...

scalaz.Equal for path dependent types

scala,scalaz,path-dependent-type
I'm experimenting with path-dependent types and I run into a problem when trying to write a scalaz.Equal instance for it. I have the following structure: class A { class B } val a1 = new A val b1 = new a1.B // type a1.B val a2 = new A val...

Already existing functional way for a retry-until in Scala?

scala,functional-programming,scalaz
Is there a functional/Scala way to call a function repeatedly until it succeeds, while reacting to failed attempts? Let me illustrate with an example. Suppose I want to read an integer from standard-in, and retry if the user did not in fact enter an integer. Given this function: def read_int():...

N-Tuple of Options to Option of N-Tuple

scala,scalaz,shapeless
My gut tells me that nothing short of macros or complex type gymnastics can solve this question in the general case. Can Shapeless or Scalaz possibly help me here? Here is a specific instantiation of the problem with N=2, but the solution I'm looking for would hold for all reasonable...

Combine left sides from nested disjunction result type

scala,scalaz
If I have a type \/[Errs, \/[Errs, Boolean]] and want to combine two lefts (two Errs) what's the best way to make it \/[Errs,Boolean] where new Errs will be appending two Errs from two lefts from the earlier type. Errs is nothing but a case class case class Errs(errors: List[Err])...

Scalaz `Tag.apply`: How does it work?

scala,scalaz,monoids
Hi I am studying the Advanced Scala book, and I have some trouble understading this piece of code from scalaz source: object Tag { /** `subst` specialized to `Id`. * * @todo According to Miles, @specialized doesn't help here. Maybe manually specialize. */ @inline def apply[@specialized A, T](a: A): A...

How do I cleanly log to io.stdOutLines and respond to the client with a scalaz.stream.tcp server

scala,scalaz,scalaz-stream
I'm very new to both scalaz-stream and specifically scalaz.stream.tcp. I'm trying to do a very simple server for my own educational purposes. I parse the requests into commands, execute them to produce responses, and write the responses back to the client. The part I am having issues with is that...

continuously fetch database results with scalaz.stream

scala,scalaz,scalaz-stream
I'm new to scala and extremely new to scalaz. Through a different stackoverflow answer and some handholding, I was able to use scalaz.stream to implement a Process that would continuously fetch twitter API results. Now i'd like to do the same thing for the Cassandra DB where the twitter handles...

Exception with ScalaZ OptionT

scala,future,scalaz
Consider the following code which uses ScalaZ's OptionT: val answer = for { customer <- optionT(function1(codeString)) customerId <- someOptionT(Future(Seq(function2(customer))) alerts <- someOptionT(Future.sequence(function3(customerId)) } yield alerts function1 returns Future[Option[Customer]] function2 returns String function3 returns Seq[Future[Option[String]]] Meanwhile this is someOptionT def someOptionT[T](t: Future[T]): OptionT[Future, T] = optionT[Future](t.map(Some.apply)) I get the following exception...

ZipList with Scalaz

list,scala,scalaz,applicative
Suppose I have a list of numbers and list of functions to apply to numbers: val xs: List[Int] = List(1, 2, 3) val fs: List[Int => Int] = List(f1, f2, f3) Now I would like to use an Applicative to apply f1 to 1, f2 to 2, etc. val ys:...

ActionBuilder to accept IO[Result] instead of Future[Result]

scala,scalaz,playframework-2.3
I wrote a small example to use the IO monad from scalaz within the play framework. The example below works as expected: object IOAction { def apply(action:IO[Result]):Result = action.unsafePerformIO } class ExampleController extends Controller { val now:IO[DateTime] = IO { DateTime.now } def index = Action { request => IOAction...

How can I implement a Fisher-Yates shuffle in Scala without side effects?

scalaz,state-monad,st-monad,starray,scala-cats
I want to implement the Fisher-Yates algorithm (an in-place array shuffle) without side effects by using an STArray for the local mutation effects, and a functional random number generator type RNG[A] = State[Seed,A] to produce the random integers needed by the algorithm. I have a method def intInRange(max: Int): RNG[Int]...

Scala Type Based Attribute Extractor - Getter only Lens?

scala,generics,scalaz,shapeless,lenses
What is the best way to extract a type from a data container such as a case class. For example if I have a type Tagged[U] = { type Tag = U} tagged type trait PID which is a tagged Int type ProductId = Int with Tagged[PID] or scalaz style...

scalaz join operation requires type explicitly specified

scalaz
scala> Some(Some(9)) res23: Some[Some[Int]] = Some(Some(9)) scala> res23.join #plan a <console>:24: error: value join is not a member of Some[Some[Int]] res23.join ^ scala> ((Some(Some(9))):Option[Option[Int]]).join #plan b res25: Option[Int] = Some(9) thought plan a should be equivalent to plan b. why the type has to be explicitly specified? Not only this,...

For-Comprehension Example with \/ and IO

scala,scalaz
Given the following Foo case class: scala> case class Foo(x: Int) defined class Foo I check if it's a valid Foo before constructing it inside of validateFoo: scala> def validateFoo(foo: Foo): \/[String, Foo] = (if(foo.x > 0) foo.success[String] else ("invalid foo").failure[Foo]).disjunction validateFoo: (foo: Foo)scalaz.\/[String,Foo] Lastly, f creates a Foo, and...

Scalaz Lens to ReaderWriterState

scala,scalaz,lenses
Given, say case class Person(age: Int) val ageL: Lens[Person, Int] = ... How do I come up with: def incrementAge(by: Int): ReaderWriterState[Config, String, Person] while taking advantage of ageL lens. The Scalaz Lens have some utilities to create a State out of a Lens, but I'm not sure how to...

Scalaz - Unable to unapply type StateT[Future, Foo, Bar]

scala,scalaz
I had a list l of StateT[Id, MyState, Boolean]. With it i was able to do the following: case class MyState (s: String) val startState = MyState ("s") val l: List[StateT[Id, MyState, Boolean]] = ... val failed = l.sequenceU.map { x => } .map { _.foldMap (identity)(Monoid.instance (_ | _,...

How to implement simple validation in Scala

validation,scala,scalaz
Suppose I need to validate request parameters. The validation result is either Success or Failure with NonEmptyList[String]. I can probably use ValidationNel[String, Unit] but it seems a bit overkill. I guess I need a simpler abstraction (see below). trait ValidationResult object Success extends ValidationResult class Failure(errors: NonEmptyList[String]) extends ValidationResult and...

How to fold a sequence with a writer monad embedding a disjunction using combinators?

scala,scalaz
I'm making some computation that may fail, so I'm using a disjunction type as result. I have a fairly common pattern for which I've written the following function : def traverse[A, B, E](a: Iterable[A], b: B)(f: (B, A) => E \/ B): E \/ B = a.foldLeft[E\/B](\/-(b)){case (b0, a0) =>...

How to fix implicit conversion to Applicative?

scala,scalaz,applicative
This is a follow-up to my previous question I would like to generalize the implicit conversion toApplicative, which adds method <*> to any M[A=>B], where M is Applicative (i.e. there is a typeclass instance Applicative[M]) implicit def toApplicative[M[_], A, B](mf: M[A=>B])(implicit apm: Applicative[M]) = new { def<*>(ma: M[A]) = apm.ap(ma)(mf)...

How to import identity operations in scalaz?

scala,scalaz,trait
syntax.IdOps seems to have no companion object to import its implicits (see, selfless pattern), so it's hard to use that in REPL for example: scala> val selfish = new scalaz.syntax.ToIdOps{} //I don't want to do this, it feels wrong selfish: scalaz.syntax.ToIdOps = [email protected] scala> import selfish._ import selfish._ Is there...

Scalaz Kleisli usage benefits

scala,scalaz,kleisli
In scalaz Kleisli[M[_], A, B] is a wrapper of A => M[B], which allows composition of such functions. For instance, if M[_] is monad I can compose Kleisli[M, A, B] and Kleisli[M, B, C] with >=> to get Kleisli[M, A, C]. In a nutshell, Kleisli provides fancy andThens depending on...

Is Kleisli a functor, applicative, or monad?

scala,scalaz,kleisli
This question is inspired by the feedback given to my previous question Scalaz provides a wrapper class Kleisli[M[_], A, B] for a function A => M[B]. Kleisli[M[_], A, B] is a semigroup if M[_] is a semigroup. Suppose that M[_] is a functor. Is it correct that Kleisli is a...

Modeling a FSM via Process1 transducer?

scalaz,scalaz-stream
I have a state machine that I would like to model using a scalaz-stream Process1. The state machine models the message flow between a client and a server. A basic set of data types might be: sealed trait ServerState case object Disconnected extends ServerState case object Authenticating extends ServerState case...

Is there any implicit providing `some.long.expression.let(x => …)` syntax

scala,scalaz,idiomatic
For example I want to get x * (x - 1) in the end of my long expression without separating it into two lines and introducing unnecessary variables. I could achieve it with simple implicit: scala> implicit class Rich[T](x: T) { def let[U](f: T => U) = f(x)} defined class...

Scalaz === on Some

scala,scalaz
Difficulty in understanding the behaviour of === in scalaz 1. scala> 1.some === Some(1) res33: Boolean = true 2. scala> Some(1) === 1.some <console>:14: error: value === is not a member of Some[Int] Some(1) === 1.some ^ 3. scala> (Some(1):Option[Int]) === 1.some res35: Boolean = true I can understand (1)...

List[OptionT[Future, Int]] to OptionT[Future, List[A]]

scala,scalaz,monad-transformers
I'm building a List of Int using an an async computation for retrieving element: (1 to n).map(anAsyncThingy).toList where anAsyncThingy returns OptionT[Future, Int] The result is hence of type List[OptionT[Future, Int]] What I'd like to get now is an OptionT[Future, List[A]] Here's my best attempt so far (I'll add some stubs,...

Scala flattening an Option around a higher kinded type, looking for a more idiomatic approach

scala,scalaz,for-comprehension,maybe,higher-kinded-types
Given a higher Kinded Type M, and a monad type class, I can operate on values within M through a for-comprehension. Working with a function that return Options, im looking for a more appropriate way to flatten these options than the solution I have. This is as follows class Test[M[+_]:Monad](calc:Calculator[M])...