You are right: type classes in Coq are just records with special plumbing and inference (there's also the special case of single-method type classes, but it doesn't really affect this answer in any way). Therefore, the only reason you would choose type classes over "pure" dependent records is to benefit...

Yes. You've concluded correctly. Since Int -> Int -> Ordering is curried, it can be seen as a function of one argument, which returns another function. I.e.: Int -> (Int -> Ordering) Hence the compiler resolves the Monoid instances in three steps: Value Type | Monoid Instance --------------------------|--------------------------- Int ->...

You create a trait for the typeclass you want to define e.g. trait Printable[T] { def print(p: T): String } then you can define implicit instances of this trait for the types you want: object Instances { implicit val UserPrintable = new Printable[User] { def print(u: User) = u.name }...

haskell,design-patterns,data-structures,typeclass

Your particular example could be solved by using ^-^ and liftI2 (/) instead of - and / respectively. This reduces the constraint to (Foldable f, Metric f, Ord a, Floating a). Using ConstraintKinds you can make constant aliases to reduce cluster: type OrderedField a = (Ord a, Floating a) type...

haskell,typeclass,function-overloading

It is easy to do in this particular case. Simply: instance a ~ Int => Foo (String -> a) where foo = length ...

scala,type-inference,typeclass

I'm not sure I fully understand your question. As far as choosing fooAny vs fooKV, the instance of Foo must be known and passed appropriately from the site where the types are known. This would be the place where mymap is called. Foo is not passed as a parameter though....

This is a slightly confusing question, as "I want to check" hints that you might want to find this out dynamically. Haskell will check all types at compile time, including membership of typeclasses. So to check if a literal is of a type that supports Eq, you simply need to...

haskell,typeclass,type-constraints,type-families

This should work: class NoConstraint a where instance NoConstraint a where instance Queue LIFO NoConstraint where ... The above defines a constraint which is satisfied by all types. As such, the obligations c a where c = NoConstraint can always be discharged. Also, since there are no members in that...

haskell,instance,show,typeclass

Add an instance declaration for the Show class. instance Show LExpr where show = show' And remove the deriving(Show) part data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq) ...

haskell,types,equality,typeclass

We can define that in terms of both Eq and Typeable from Data.Typeable. We can compare the types of things that are Typeable to check that they are the same type. (?==) :: (Eq b, Typeable a, Typeable b) => a -> b -> Bool x ?== y = cast...

The Haskell Report restricts what's allowed to appear in typeclass instances (by default) (Section 4.3.2) ... The type (T u1 … uk) must take the form of a type constructor T applied to simple type variables u1, … uk; furthermore, T must not be a type synonym, and the ui...

haskell,typeclass,haskell-platform

but isn't every member of Floating also a member of Ord? The obvious counterexample are complex numbers. Also, some types that give good Num etc. instances don't allow equality or inequality comparisons at all, because they represent more than just a single number value, but e.g. a generic abstraction...

haskell,graph,polymorphism,typeclass

Your type class can be fixed by including the type parameters v and w in the class definition. class Edge e where endpoints :: e v w -> (v,v) weight :: e v w -> w Now e has the kind * -> * -> * meaning that it needs...

haskell,functional-programming,typeclass,currying

What you're trying to do boils down to this: f :: Either a Bool -> Either a () f (Right _) = Right () f left = left with error: foo.hs:3:7: Couldn't match type ‘Bool’ with ‘()’ Expected type: Either a () Actual type: Either a Bool In the expression:...

Does it simply mean that t supports and implements the functions specified by Eq ? Yes, precisely. It simply means that there's an instance of Eq t which defines the operator (==), as required by Eq. You can therefore use said operator on type t in your code. A...

You ended the definition of C2_nat with Qed. Definitions ending with Qed are opaque and cannot be unfolded. Write the following instead Instance C2_nat: C2 nat:= {v2:=4}. trivial. Defined. and your proof finishes without problems....

scala,code-generation,typeclass,shapeless

There's one tricky step, but you definitely can define your own LabelledGeneric instances. For the sake of example here I'll use Alex Archambault's argonaut-shapeless library, which doesn't literally use TypeClass, but it does use LabelledGeneric, and the principle is the same. First for our class: class Foo(val i: Int, val...

Just define the method like you do in your own example: def foo[A : Addable](x: A) = implicitly[Addable[A]].add(x) ...

I’m not sure I understand the motivation, but yes, you can express this with GHC’s ConstraintKinds extension: {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeclasses #-} {-# LANGUAGE UndecidableInstances #-} import GHC.Exts (Constraint) class List (c :: * -> Constraint) a data Nil...

scala,type-inference,typeclass,implicits

The issue here is that scala cannot infer the O type because it is not present in Insert // I is in the parameter list but there is no O to be found case class Insert[I, O](arg: I)(implicit evidence: Ordering[O]) This leaves the compiler no choice but to infer O...

No, this isn't possible since Haskell's type classes are always open: the compiler can never prove some instance does not exist, since somebody might still add it any time later.

scala,typeclass,implicit,companion-object,implicit-typing

change the name of one of your implicit functions so they aren't both named: fractionalDivisible

scala,pattern-matching,type-inference,typeclass

There are two issues getting in the way, one with the scoping of view and context bounds, the other with type erasure. 1. Scoping These: case class GreaterThan[T <% Ordered[T]]( a:Expr[T], b:Expr[T]) extends Expr[Boolean] case class GreaterThan[T : Ordering]( a:Expr[T], b:Expr[T]) extends Expr[Boolean] Are syntactic sugar for: case class GreaterThan[T](...

The closest we are able to get is a Class1 class that reifys the relationship between a class and a single superclass constraint as a class. It's based on the Class from constraints. First, we'll take a short tour of the constraints package. A Dict captures the dictionary for a...

haskell,configuration,yesod,typeclass

I'm going to simplify the problem so that we only need core libraries. We want to change how we Show a MarkdownText based on some ExampleSettings that contain a prefix and a suffix. {-# LANGUAGE OverloadedStrings #-} import Data.Text as T import Data.Monoid import Data.String newtype MarkdownText = MarkdownText {...

After banging on this problem for a few more days, I have typeclass inheritance of different Kinds that, as far as I can tell, is correct. I was on the right track in my question update. All I needed to do was add an explicit inheritance of Semigroup. I am...

Scala has a typeclass for this called Numeric with implementations for the usual JVM number types. note: it doesn't satisfy the Number[A] + Number[B] scenario Examples Below If you want to define your own number type, e.g. case class RationalNumber(numerator: Int, denominator: Int) Then you would also implement a Numeric...

The only instance for Info with any code is the one for Cat, so the only possible value of the second element of the tuple is the result of show (a :: Cat) which is invariably "Cat \"...\"". The Info instance for Dolphin came from GeneralizedNewtypeDeriving; it does exactly what...

haskell,typeclass,type-systems

When trying your example in GHC 7.8.3 >>> meh 1 I get: <interactive>:2:1: No instance for (Meh a0) arising from a use of ‘meh’ The type variable ‘a0’ is ambiguous Note: there are several potential instances: instance Meh Unknown -- Defined at Meh.hs:9:10 instance Meh Int64 -- Defined at Meh.hs:7:10...

The type of x is underconstrained, which is why there is an unknown type variable appearing in the error message. psc will not try to instantiate a type variable when searching for a type class instance. This can sometimes be an issue when using multi parameter type classes without something...

haskell,graph,typeclass,contract,foldable

There are currently very few Foldable laws, so you can do all sorts of things. In fact, there are several different Foldable instances you could write, corresponding to different traversal orders. The Foldable laws describe relationships among the different Foldable members and, if the type is also a Functor, an...

The tai parameter is fixed to Double because of your datatype. Change it to data Method a = Ndiv Int | Size a for example, then your function should typecheck, although you'll need a stronger constraint than Num, as cieling requires RealFrac. The type will be function :: RealFrac a...

Another solution, which requires no extensions, is to use a higher-kinded class. Thus: class Vector v where vplus :: Num a => v a -> v a -> v a vnegate :: Num a => v a -> v a Then it's easy to add a dot-product method: dot ::...

haskell,types,functional-programming,ghc,typeclass

This error occurs because when you call mid (), it has the type Monoid () p0 (->) m => i -> m, and there is nothing constraining p0 to be the particular p you chose since p0 does not appear on the right hand side of the => sign in...

haskell,lambda,instance,show,typeclass

Add an instance declaration for the Show class. instance Show LExpr where show = show' And remove the deriving(Show) part data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq) ...

This is an instance of GHCi’s defaulting rules. When it encounters an ambiguous type, it selects () (“unit”) as the default. So it’s attempting to read 10 as a value of type (), which fails to parse. The type is ambiguous because read’s return type is overloaded to work on...

haskell,functional-programming,functor,typeclass

Your second Functor instance also doesn't make any sense. The biggest reason why Set can't be a Functor in Haskell is fmap can't have constraints. Inventing different notions of equality as StrongEq doesn't change the fact that you can't write those constraints on fmap in your Set instance. fmap in...

you have to fully qualify No, not fully qualify. Consider: import qualified Algebra.Additive as Add myadd :: Add.C a => a -> a -> a That looks fairly readable to me. EDIT: Also consider making a superclass and treating that as an alias: class (Add.C a, Ring.C a) =>...

A simple example where the Fundep version still works, but not the single-parameter one, is a Set container: import qualified Data.Set as Set instance (Ord e) => Collection (Set.Set e) e where insert = Set.insert member = flip Set.member An instance to the other class doesn't work because you need...

I don't know much about type classes myself, but doesn't B need to be variable? By separating it from foldr, you're making it fixed. I think it only makes sense to make C and A fixed. Class Foldable (C : Type -> Type) (A : Type) (foldr : forall B,...

haskell,functional-programming,typeclass

You just forgot some parens :) instance Show Fruit where show Apple = "Hey Apple" show (Orange a) = show a ++ " number of Orange" Patterns like Orange a need parens to disambiguate from something like Apple a where we really have two arguments....

Update If you only want to define AS[I, P] instances for particular values of I and P, that's also possible—you can define ASQueryBuilder as in your question, and then require an instance in your methods that use the type class: def func(a: A, s: S)(implicit bq: BuildableQuery[AS[A, S]]): QueryBuilder =...

scala,inheritance,functional-programming,typeclass

When using inheritance to achieve ad-hoc polymorphism we may need to heavily pollute the interface of our value objects. Assume we want to implement a Real and a Complex number. Without any functionality, this is as simple as writing case class Real(value: Double) case class Complex(real: Double, imaginary: Double) Now...

haskell,types,monads,typeclass

It's much more symmetric if you think in terms the following derived function (from Control.Monad): (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c) (f >=> g) x = f x >>= g The reason this function is significant is...

(<.>) :: Num b => a -> a -> b The above means that (<.>) is able to produce any type of number the caller of that function might want. For instance, if x,y are Vec2 Double, then x <.> y can be called to return Integer. The compiler then...

In the context of your problem, you should introduce a subtract method into your Operations trait, so that you can provide evidence that T has such a method (well it doesn't, but a method that does a subtraction from to T from another). sealed trait Operations[T] { def add(a: T,...

I think there are a few elements in tension here. There's the general idea that type class definitions ought to be minimal, and only contain independent functions. As bhelkir's answer explains, if your class supports functions a, b and c, but c can be implemented in terms of a and...

Type class instantiations in Isabelle always introduce new constants for the parameters of the type class. Thus, you cannot say that plus (written infix as +) shall be the same as Plus. However, you can go the other way around, namely instantiate the type class first and only later declare...

You need a functional dependency here: use class Eq b => HasPK a b | a -> b where getPK :: a -> b and enable whatever extension GHC points to. The issue lies in the possibility of having multiple PKs for the same type, as in instance HasPK MyType...

haskell,compiler-errors,typeclass

Are you importing Data.UUID.Aeson (from the uuid-aeson package)? This works for me: import Data.UUID import Data.UUID.Aeson import Data.Aeson type MyUUID = UUID data U2 = U2 MyUUID Int instance ToJSON U2 where toJSON(U2 a b) = toJSON a ...

scala,types,typeclass,implicit

This isn't a case of some deep type system voodoo, but rather the different way that constructor parameters are used in Scala. Changing your class header to implicit class GenBuilder[T](val self: T)(implicit f: FooLike[T]){ (note the val self) will make self a field of the GenBuilder, rather than just avaliable...

You're still using the value constructor. You can use types that have record fields without having to use the record syntax to construct them, so Frank x does the same thing as Frank { frankField = x }. If you have more than one record field, e.g.: data Frank a...

haskell,yesod,typeclass,persistent,monad-transformers

Turns out I didn't realize you needed to repeat constraints inside of functions as well. This worked: _ <- rawSql "SELECT ?? FROM my_entities WHERE id = ? FOR UPDATE" [toPersistValue somethingId] :: MonadIO m => SqlPersistT m [Entity MyEntity] ...

You don't want to do that. The simplest way of achieving what you want is the following: class HasId a where getId :: a -> UUID class HasId a => MyClass1 a where method1 = -- NOTE: Use "getId" instead of plain "id". when you define your data types you...

First, let me suggest that instead of an own Wrapper type, you use Data.Tagged.Tagged, whose purpose is exactly this kind of stuff. Apart from that, you need to turn on the -XScopedTypeVariables extension, otherwise the a type variable only exists in the type signature itself, but not in signatures of...

haskell,types,typeclass,type-signature

There is (if we neglect unboxed types) only one kind whose types actually have any values: *. All other kinds don't contain types as such, but just "type-level entities". The compiler can use those to determine what to do with the actual types and their values around, but it's never...

haskell,types,typeclass,existential-type

First of all, to reference type variables in the type signature from the body of the function, you need to enable ScopedTypeVariables, and add a forall to the type: {-# LANGUAGE ScopedTypeVariables #-} display :: forall a c . (HasComponent (DisplayData a) c, HasComponent (Displayer a) c) => Entity c...

haskell,operator-overloading,typeclass

The Bar class is about being able to convert to anything that IsString. I presume the Monoid instance is there for some sort of efficiency. We could give Bar and bar more illuminating names. class ToStringPlus a where toStringPlus :: ( IsString b, Monoid b ) => a -> b...

Backwards compatibility would be completely destroyed, really. If you have a simple method like: def foo[A](a: A)(implicit something: SomeType) = ??? Then suppose that in the next version of Scala, the compiler suddenly added implicit ClassTags to the signature of all methods with type parameters. This method would be broken....

Monomorphism restriction If you have MonomorphismRestriction enabled, then sometimes you will need to add a type signature to get the most general type: {-# LANGUAGE MonomorphismRestriction #-} -- myPrint :: Show a => a -> IO () myPrint = print main = do myPrint () myPrint "hello" This will fail...

haskell,monads,typeclass,functor,applicative

There's a lot of questions rolled into one here. But let's take them one at a time. First: why doesn't the compiler look at instance contexts when choosing which instance to use? This is to keep instance search efficient. If you require the compiler to consider only instances whose instance...

Don't you mean...? instance (GDefault a, GDefault b) => GDefault (a :+: b) where ... -- ^ ^ ...

The Show typeclass actually has three member functions, show, showsPrec, and showList. In the instance for Show Char, the showList function is overloaded to output quote marks and shove all the letters together without delimiters: From GHC.Show: instance Show Char where showsPrec _ '\'' = showString "'\\''" showsPrec _ c...

The problem is that you have defined (==) to be recursive on itself. Simplifying your definition a little, you have: m == n = chop m == chop n This evaluates like so: m == n -> { definition of (==) } chop m == chop n -> { definition...

AdditionServer is the object which is extending Transformer. In your code, this object is not defining neither extractPayload nor responsePayload thus the compilation error you get. You should move your methods definitions from the trait companion object to AdditionServer object AdditionServer extends App with Transformer[HttpRequest,Add,Result,HttpResponse] { import Transformer._ def extractPayload(r:HttpRequest):Add...

Consider the following: newtype ProcessID = PID Int deriving Eq What this does is write an instances that looks like instance Eq PID where (PID x) == (PID y) = x == y In other words, when you call == on a PID, it unwraps it into an ordinary Int,...

haskell,compiler-errors,instance,equality,typeclass

It isn't clear what you are trying to achieve. Here are some thoughts: When you declare an instance of a class like instance (Eq a) => PartOrd a, you are expected to provide implementations for the functions in PartOrd a (ie partcmp, not == and \=). The compiler is telling...

scala,haskell,typeclass,implicit,existential-type

You got it almost right: import scalaz._ import scalaz.Scalaz._ trait Obj { type T // existential type val x: T implicit val show: Show[T] } implicit val objSow: Show[Obj] = Show.shows[Obj] { (x: Obj) => x.show.shows(x.x) } object Obj { /* "constructor" */ def apply[U](_x: U)(implicit _show: Show[U]): Obj =...

I don't know whether this is a bug or not, but notice that when you write something like Functor F -> SomeType, you are implicitly saying that SomeType does not depend on the Functor instance, which is not true in your case: the full type of your theorem, printing all...

You can't match against a typeclass value like this. Typeclasses abstract over the actual underlying type while pattern matching would expose it. However, you can still get the same behavior and some nice syntax with the ViewPatterns extension. The idea is to include a function which takes your abstract value...

Missing indentation. Indent your code. Wrong instance Fractional Physical where (Physical v1 u1) / (Physical v2 u2) = (Physical (v1 / v2) (sqrt((u1 /v1)^2 + (u2 /v2)^2)*(v1 /v2))) Correct instance Fractional Physical where (Physical v1 u1) / (Physical v2 u2) = (Physical (v1 / v2) (sqrt((u1 /v1)^2 + (u2 /v2)^2)*(v1...

scala,generics,typeclass,implicit

Prepend an empty parameter list: def read[T]()(implicit e: Reader[T]): T = e.read(iterator) def readByte(): Byte = this.read[Byte]() // <- HURRAY IT WORKS Removing the argument list (()) at the call site also works, but is typically frowned upon because syntactically argumentless calls are expected to be referentially transparent....

haskell,pattern-matching,typeclass

Given the definition of VectorFeatureSet, the constructor VFS has type [fl] -> VectorFeatureSet fl, i.e. the value it "contains" will be a list of fl. In your instance for FeatureSet, getFeatures should have type VectorFeatureSet fl -> fl. So when you write getFeatures (VFS fl) = fl, you are returning...

haskell,typeclass,gadt,constraint-kinds

An open variant of Daniel Wagner's answer would use a TypeFamily to let each type that implements the class specify a context that it needs. {-# LANGUAGE GADTs #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} import GHC.Exts (Constraint) import Data.Proxy data Dict c where...

scala,typeclass,read-eval-print-loop,implicit

It's a job for a good IDE. IntellijIDEA 14+ Check out Implicits analyser in Scala Plugin 1.4.x. Example usage: def myMethod(implicit a: Int) = { } implicit val a: Int = 1 myMethod // click the myMethod and press Ctrl+Shift+P, the "Implicit Parameters" is shown Eclipse Check out Implicit highlighting....

scala,operators,implicit-conversion,typeclass,implicit

I moved a bunch of little things to get things to work. I tried to comment most places I made changes to get it running. import language.implicitConversions import scala.util.{Try, Success, Failure} // you need to wrap this all in an object, since you can't have vals at the top level...

Arrow is basically the class for monoidal categories1 – with “monoid” not referring to Monoid, but the product-monoid of Haskell types. I.e., with unit element () and multiplication (,). Now, sum types make up a monoid as well, and that's what ArrowChoice uses. These two classes are in that sense...

What you're looking is Heterogenous collections IMHO the best way is to use existentials, as described on wiki: {-# LANGUAGE ExistentialQuantification #-} data Showable = forall a . Show a => MkShowable a pack :: Show a => a -> Showable pack = MkShowable hlist :: [Showable] hlist = [...

scala,generics,types,typeclass,type-parameter

You can provide an implicit function with the required type: implicit def SeqMonoid[T]: Monoid[Seq[T]] = new Monoid[Seq[T]] { override def op(a: Seq[T], b: Seq[T]): Seq[T] = a ++ b override def id: Seq[T] = Nil } ...

GHCi is a little bit peculiar. In particular, when you type an expression at the prompt, it tries to interpret it in two different ways, in order: As an IO action to execute. As a value to print out. Since IO is Applicative, it is interpreting pure A as an...

haskell,typeclass,type-families

You can use a class: {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts #-} class (F (f x) ~ g x) => F'Eq f g x instance (F (f x) ~ g x) => F'Eq f g x bar' :: forall f g. (Forall (F'Eq f g)) => forall a b. f a...

scala,generics,implicit-conversion,typeclass,implicit

You're really close, actually. You need to remove the parentheses from seqBoxer[A]. Otherwise, the compiler sees this as an implicit conversion from () => Boxer[Seq[A]], rather than simply an available implicit Boxer[Seq[A]]. For good measure, it is also a good idea to make the return type of an implicit method...

scala,record,typeclass,shapeless

You were very close—you just need to add FieldType[K, H] at each inductive step instead of H and use field[K] to type the values you get from the Monoid[H] appropriately: import com.twitter.algebird._ import shapeless._, labelled._, record._, syntax.singleton._ implicit val hnilGroup: Group[HNil] = new ConstantGroup[HNil](HNil) implicit val hnilMonoid: Monoid[HNil] = hnilGroup...

haskell,composition,functor,typeclass

Yep, and you would just add that as a constraint for your instance instance (Show (f (g a))) => Show (FComp f g a) where show (C f) = "FComp " ++ show f This just means we have a show instance for FComp exactly when we have one for...

When you are executing: cmp i1 i2 Haskell infers the type of i1 and i2 to be Set [Integer]. And since cmp has type: cmp :: (Comparable a) => a -> a -> String Integer has to have an instance of the Comparable type class; which it doesn't. So to solve...

haskell,polymorphism,overloading,typeclass

The problem you're facing is that the overloading is determined by all of the types in the class—including ones that only appear as return types. You could have instances for both MyClass Bool Int and MyClass Bool String, and it would be able to disambiguate based on what type is...

No, this isn't possible (as of 7.8.3, and I think also 7.10); it's GHC bug #7543. It's not a very trafficked bug; there are clearly at least a few people who'd like to be able to write this sort of thing (e.g., you, Edward Kmett), but mostly this goes unnoticed....

A type family could be handy: {-# LANGUAGE TypeFamilies, KindSignatures, DataKinds, TypeOperators, ConstraintKinds #-} import qualified Data.Vector.Generic as G import GHC.Prim type family Vectors v (a :: [*]) :: Constraint where Vectors v '[] = () Vectors v (a ': as) = (G.Vector v a, Vectors v as) This creates...

You need to define fun1 like this. def fun1[A](a: A)(implicit converter: Converter[A, Int]) = fun2(a, 42) In Scala, the type inference does not "flow backwards", only from left to right and top to bottom. So, the usage of fun1(1) is not considered for the implicit resolution for fun1 – it...