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...

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...

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...

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...

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...

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...

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...

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...

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...

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...

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:...

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...

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...

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, +...

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...

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=...

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...

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)...

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 ::...

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...

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 ::...

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,...

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...

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...

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...

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...

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...

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...

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,...

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...

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...

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...

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...

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...

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(...

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...

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 =...

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...

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...

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...

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 ->...

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...

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...

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...

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!...

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 =...