FAQ Database Discussion Community


A typeclass instance that needs configuration data. What are my options?

haskell,configuration,yesod,typeclass
Using yesod and persistent, I made what I think is a handy type to handle Markdown data: {-# LANGUAGE OverloadedStrings #-} module Utils.MarkdownText where import Prelude import Data.Text.Lazy import Data.Text as T import Database.Persist import Database.Persist.Sql import Text.Blaze import Text.Markdown newtype MarkdownText = MarkdownText { rawMarkdown :: T.Text } instance...

Instance of Show for Lambda

haskell,lambda,instance,show,typeclass
So, I have already defined the lambda data type as such: data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq, Show) Now I want to implement an instance of Show myself. I have already the function...

Guessing the correct instance of Num from the context

haskell,typeclass,type-systems
Suppose: import Data.Int (Int64) data Unknown class Meh a where meh :: a -> String instance Meh Int64 where meh = show instance Meh Unknown where meh _ = "Unknown" It is obvious that meh can only take either an Int64 or an Unknown. But we all know that meh...

Why do we have to explicitly specify the ClassTag typeclass

scala,typeclass,scala-reflect
Now that scala has iterated towards a JVM type erasure fix with the ClassTag typeclass, why is it an opt-in, rather than having the compiler always capture the type signature for runtime inspection. Having it an implicit parametrized type constraint would make it possible to call classTag[T] regardless of the...

How to specify type for class constrained value?

haskell,yesod,typeclass,persistent,monad-transformers
I'm trying to use a type signature on the result of the following persistent call. I can't figure out how to define the signature for something that's parameterized and class constrained such as the m inside of the transformer below: saveMyStuff :: MonadIO m => Int -> SqlPersistT m Stuff...

Coq: typeclasses vs dependent records

typeclass,coq
I can't understand the difference between typeclasses and dependent records in Coq. The reference manual gives the syntax of typeclasses, but says nothing about what they really are and how should you use them. A bit of thinking and searching reveals that typeclasses essentially are dependent records with a bit...

Specifying a constaint for a class

haskell,typeclass
I have three data declarations in the different modules: data Data1 = Data1 { id :: UUID , field2 :: String , field3 :: Int } data Data2 = Data2 { id :: UUID , field1112 :: String , field4433 :: String } data Data3 = Data3 { id ::...

Haskell ghci read behaviour with * and max

haskell,types,typeclass
So I've just encountered the following in ghci: (*) (read "10") (read "20") returns 200 as expected. However, this line (max) (read "10") (read "20") throws an exception: *** Exception: Prelude.read: no parse And I can't really figure out the cause for such ghci behaviour. Any help would be appreciated!...

Product and Sum Type Parallels in Haskell Type Classes

haskell,types,typeclass
It appears that type classes such as Applicative, Monad and Arrow have some sort of sum type equivalent in type classes such as Alternative, MonadPlus and ArrowPlus respectively. For example, Applicative and Alternative can be used to define the following: (<&&>) :: Applicative f => f a -> f b...

Translate/encode Haskell's `data Obj = forall a. (Show a) => Obj a` in Scala

scala,haskell,typeclass,implicit,existential-type
I've not been able to come up with how to encode Obj in Scala: {-# LANGUAGE ExistentialQuantification #-} data Obj = forall a. (Show a) => Obj a instance Show Obj where show (Obj a) = "Obj " ++ show a main = print $ show [Obj "hello", Obj 3,...

Choose a typeclass based on return type

haskell,typeclass
I want to be able to have a function, which implementation will choose a typeclass based on the manual type specification of it's return type. Here's a contrived example: a typeclass and two instances: class ToString a where toString :: a -> String instance ToString Double where toString = const...

Wrong argument kind when using GHC Generics

haskell,types,ghc,typeclass
I've been following the GHC.Generics tutorial to make a simple generic typeclass for providing default values for arbitrary types. However when I try to load my file (relevant snippet, which still produces the error) {-# LANGUAGE DefaultSignatures, DeriveGeneric, TypeOperators, FlexibleContexts #-} import GHC.Generics class Default a where def :: a...

Using a typeclass to access fields of similar data types in Haskell

haskell,graph,polymorphism,typeclass
I am in the process of working on some graph problems in Haskell. In the middle of my work, I decided that I wanted to be able to represent edge colors within a graph data type. So I started with edges: Edges could be either colored or uncolored. Here's a...

Why isn't Scala picking the most specific instance in this this type class?

scala,type-inference,typeclass
I am struggling to build this computation pipeline builder in Scala. I want a class that has two methods, map and reduce, that receive anonymous functions in a "fluent interface". These functions will be composed, so I want to type-check all of them, also having their input type inferred from...

Resolving ambiguities for overloaded functions

haskell,typeclass,function-overloading
I want to have an overloaded function in Haskell. {-# LANGUAGE FlexibleInstances #-} class Foo a where foo :: a instance Foo (String -> Int) where foo = length instance Foo String where foo = "world" However such overloading deals very poorly with type ambiguities. print $ foo "hello" would...

Defining partially applied typeclasses

haskell,typeclass
Exploring the idea that typeclasses are essentially C++ abstract classes without nested inheritance, I have written the typeclass class Interface i c where i :: c -> i instance Interface i i where i = id infixl 1 # (#) :: Interface i c => c -> (i -> r)...

Why are instances matched only by their heads?

haskell,monads,typeclass,functor,applicative
I'll start by introducing a concrete problem (StackOverflow guys like that). Say you define a simple type data T a = T a This type is a Functor, Applicative and a Monad. Ignoring automatic deriving, to get those instances you have to write each one of them, even though Monad...

How to pattern match against a typeclass value?

haskell,typeclass
Suppose that I define a typeclass in Haskell, class (Bool a) where false :: a true :: a In order to define a generic not operation for any Bool, one would need to pattern match against its potential values: not :: Bool a => a → a not true =...

How does GHCi print partially-applied values created from “pure”?

haskell,typeclass,applicative
I've been playing around with Applicative instances in order to figure out how they work. However, I honestly don't understand this behavior. If I define my own datatype, then apply pure to it with no other arguments, nothing prints out, but it errors if I try to apply something to...

How to provide a default typeclass for generic types in Scala?

scala,generics,types,typeclass,type-parameter
In Scala, if you create a typeclass, say the algebraic structure Monoid[T], you can provide many default typeclass implementations for different types that are monoids. Suppose a monoid is defined as: trait Monoid[T] { def op(x: T, y: T): T def id: T } Since Strings under the concatenation operation...

Can I parameterise the empty constraint type?

haskell,typeclass,type-constraints,type-families
I have a class for queues which allows the instance to define the constraints it places on the elements. For example, a priority queue requires its elements to be orderable: {-# LANGUAGE MultiParamTypeClasses, ConstraintKinds, FunctionalDependencies #-} class Queue q c | q -> c where empty :: q a qpop...

Define a Typeclass for Shapeless Records

scala,record,typeclass,shapeless
I'm trying to learn Shapeless, and I would like to define a monoid which adds together instances of shapeless records. Note that I'm using algebird monoids (not scalaz), but I'm sure they're quite similar. Here's an example of what I'd like to be able to do: val result = Monoid.sum(...

Scala Typeclasses with generics

scala,generics,implicit-conversion,typeclass,implicit
I've been playing with the typeclass pattern in Scala, but I haven't been able to figure out how to implement the implicit companion object when the type I'm working with is generic. For example, let's say I've defined a trait for a typeclass that provides functions for putting things into...

Representing arbitrary implementations of a typeclass in Haskell

haskell,typeclass
I'm trying to overcome years of working within the classic Java-style inheritance model to truly get comfortable with Haskell. It hasn't been going well, and I need a bit of help. Suppose I have a typeclass Foo. I want to represent a list of arbitrary implementing classes of Foo, but...

Not deducible relationship

haskell,typeclass
Why the relationship between a and b is not deducible? class Vector a where (<.>) :: Num b => a -> a -> b data Vec2 a = Vec2 (a, a) deriving Show instance Num a => Vector (Vec2 a) where Vec2 (a, b) <.> Vec2 (c, d) = a...

Existing constants (e.g. constructors) in type class instantiations

typeclass,isabelle
Consider this Isabelle code theory Scratch imports Main begin datatype Expr = Const nat | Plus Expr Expr it is quite reasonable to instantiate the plus type class to get nice syntax for the Plus constructor: instantiation Expr :: plus begin definition "plus_Exp = Plus" instance.. end But now, +...

Haskell ad hoc polymorphism

haskell,polymorphism,overloading,typeclass
I'm trying to get my head around ad-hoc polymorphism in haskell, that is having the same function provide different behaviour for different argument types. But while the following test code compiles {-# LANGUAGE MultiParamTypeClasses #-} class MyClass a b where foo :: a -> b instance MyClass Bool Int where...

Type classes, instances and wrappers

typeclass,purescript
can somebody explain to me why this(version 1) compiles while the version below(version 2) does not. -- version 1 (compiles) module Chapter2 where import Debug.Trace data Wrapper a = Wrapper a instance showWrapper :: (Show a) => Show (Wrapper a) where show (Wrapper w) = "Wrapper ( " ++ (show...

How can I 'discover' type classes/implicit values in the current scope?

scala,typeclass,read-eval-print-loop,implicit
I've made use of a few of scala's built-in type classes, and created a few of my own. However, the biggest issue I have with them at the moment is: how do I find type classes available to me? While most of those that I write are small and simple,...

Typeclasses: function with default implementation vs separate function

haskell,typeclass
When defining a typeclass, how do you decide between including/excluding a function in the typeclass' definition? For example, what are the differences between these 2 cases: class Graph g where ... insertNode :: g -> Node -> g insertNode graph node = ... vs class Graph g where ... insertNode...

Use instance type parameter in type class

haskell,typeclass
As an exercise, I'm trying to create a Vector typeclass as an exercise: class Vector v where vplus :: v -> v -> v vnegate :: v -> v type V3 a = (a,a,a) instance (Num a) => Vector (V3 a) where (a,b,c) `vplus` (d,e,f) = (a+d, b+e, c+f) vnegate...

Could not deduce (a ~ Double) with Haskell

haskell,types,ghc,typeclass
I have a typing problem with a Haskell function. I implemented this (simplified) function : function (xa,ya,za) (xb,yb,zb) (Size tai) = function (xa,ya,za) (xb,yb,zb) (Ndiv ndiv) where ndiv = ceiling (leng / tai) leng = sqrt((xb-xa)**2+(yb-ya)**2+(zb-za)**2) data Method = Ndiv Int | Size Double It working well if I give...

Why prefer Typeclass over Inheritance?

scala,inheritance,functional-programming,typeclass
According to this Erik Osheim's slide, he says the inheritance can solve the same problem as typeclass would, but mentions that inheritance has a problem called: brittle inheritance nightmare and says the inheritance is tightly coupling the polymorphism to the member types What is he means? In my opinion, Inheritance...

How to put constraints on type variable of kind `Constraint`?

haskell,ghc,typeclass,gadt
I'm playing around with the ConstraintKinds extension of GHC. I have the following data type, which is just a box for things fulfilling some one parameter constraint c: data Some (c :: * -> Constraint) where Some :: forall a. c a => a -> Some c For example, I...

Type constraints become huge and unreadable for simple code

haskell,design-patterns,data-structures,typeclass
Mind the following code: -- A n-dimensional axis aligned bounding box. data AABB v a = AABB { aabbMin :: !(v a), aabbMax :: !(v a) } deriving (Show) -- `v` is a container, representing the number of dimensions. Ex: -- type Box2DFloat = AABB V2 Float -- type Box4DFloat...

Implicit def type classes from other type classes

scala,typeclass,implicit,companion-object,implicit-typing
I want to add a new implicit type class Divisible for every type T that already has either an implicit Fractional or Integral type classes. The code I wrote does not compile: object Divisible { implicit def fractionalDivisible[T](implicit frac: Fractional[T]): Divisible[T] = new Divisible[T] { override def div(x: T, y:...

Managing explosion of constraints (Haskell)

haskell,constraints,typeclass
I am writing a function which I would like to be generic over Vectors. In other words, I have something like: import qualified Data.Vector.Generic as G foo :: (G.Vector v a, G.Vector v b, G.Vector v c, G.Vector v d) => v a -> v b -> v c ->...

Floating, Ord and RealFloat in Haskell

haskell,typeclass,haskell-platform
I'm trying to figure out why this does not compile yell :: (Floating a) => a -> [Char] yell x | x > 10.0 = "Yelling" | otherwise = "No Yell" but this yell :: (Floating a, Ord a) => a -> [Char] yell x | x > 10.0 =...

Inferring Eq typeclass

haskell,typeclass
I'm writing a CRUD like application and have a lot of lookups by primary key(primary keys can have different types). So I defined following typeclass: {-# LANGUAGE MultiParamTypeClasses #-} class Eq b => HasPK a b where getPK :: a -> b Now I can write: import Data.Maybe lookupPK ::...

How to have generic numeric type in scala for addition and multiplication?

scala,typeclass
I'm trying to implement generic numbers in scala that support addition and multiplication, can pattern match to any number and aren't restricted to any one type like Int, Double, etc. I looked up the docs and found that java.lang.Number fits the last criteria, i.e, any number pattern matched against java.lang.Number...

Haskell: `==' is not a (visible) method of class

haskell,compiler-errors,instance,equality,typeclass
So, when I compile the following piece of code edited: instance (Eq a) => PartOrd a where [] == [] = True (x:xs) == (y:ys) = x==y && xs==ys _==_ = False xs /= ys = not (xs == ys) I get: `==' is not a (visible) method of class...

How to add equality comparisons (==) to a newtype in Haskell

haskell,typeclass,newtype
I'm trying to define a newtype called "Poly" in Haskell, where the type is a list of a "Num"s that represents a polynomial expression. [1,2,3] corresponds to 3x^2 + 2x + 1, so therefore [4,5,6,0,0...0] is the same polynomial as [4,5,6]. I've created a helper function called "chop" to remove...

Traits not implemented in finagle service

scala,typeclass,trait,finagle
I have a simple finagle service as follows: import com.twitter.finagle.{Http,Service} import com.twitter.util.{Await, Future} import java.net.InetSocketAddress import org.jboss.netty.handler.codec.http._ import org.jboss.netty.buffer.ChannelBuffers.copiedBuffer import org.jboss.netty.util.CharsetUtil import net.liftweb.json._ import com.twitter.finagle.http.{Request,Response,RichHttp} import com.twitter.finagle.builder.ServerBuilder case class Add(num1:Int, num2:Int) case class Result(result:Int) trait Transformer[R1,T,U,R2] { def...

How to Rewrite Function Using Context Bounds?

scala,typeclass
Given the following Addable type-class: scala> trait Addable[A] { | def add(x: A): A | } defined trait Addable I created an instance for Int: scala> class AddInt(x: Int) extends Addable[Int] { | override def add(y: Int) = x + y | } defined class AddInt Then, I created an...

What does “No instance for (Comparable Integer)” mean?

haskell,typeclass
data Set a = Set [a] i1 = Set [1, 2, 3] i2 = Set [3, 2, 1] member xs x = elem x xs subset xs ys = and (map (member ys) xs) instance (Eq a) => Eq (Set a) where (Set xs) == (Set ys) = (subset xs...

scala value is not a member of type parameter

scala,typeclass
I'm trying to get the hang of Scala traits and case classes. Below is a followup to this question. Suppose I have a simple class and an object that extends it. sealed trait Operations{ def add(a:Double,b:Double):Double def multiply(a:Double,b:Double):Double } case object CorrectOperations extends Operations{ def add(a:Double,b:Double):Double = a+b def multiply(a:Double,b:Double):Double=...