Questions tagged [typeclass]
Type classes in Haskell are a language mechanism to support ad hoc polymorphism. They also exist in Scala, Coq, and Isabelle.
1,890
questions
0
votes
0
answers
26
views
Is it possible to define my own Show class and reuse instances of TextShow and Prelude.Show?
I'm trying to define my own Show class named MyShow, and want to 'steal' instances from TextShow and Prelude.Show, and prefer the former one if both exists.
I tried following (showbPrec things is ...
1
vote
3
answers
52
views
Haskell types and typeclasses declaration
I am trying to understand classes and instances in Haskell a bit better. Therefore I am looking into:
http://learnyouahaskell.com/making-our-own-types-and-typeclasses
Here they recommend trying:
...
6
votes
1
answer
99
views
Capturing typeclass dictionaries
Below is code that will happily compile (once adding the constraints package). Foo1 and Foo2 are two alternate definitions of Foo, which I can write f1 and f2 sensibly for.
However, I think Foo3 is ...
2
votes
2
answers
129
views
Error matching types: using MultiParamTypeClasses and FunctionalDependencies to define heterogeneous lists and a function that returns first element
There is a relevant question concerning Functional Dependencies used with GADTs. It turns out that the problem is not using those two together, since similar problems arise without the use of GADTs. ...
1
vote
1
answer
58
views
Reference inferred type in multi parameter type classes
I have a data type with 3 phantom types attached so i can define functions classes for each combination. This method removes much duplicate code:
newtype Dd x y z = ToDd Cudd.DdNode deriving (Eq,Show)
...
0
votes
0
answers
88
views
Parametrize return type based on concrete type of typeclass
Consider I have the following template for two typeclasses:
data TheoryParseErr = TheoryParseErr deriving (Show)
class Theory t where
applySemantics
:: (Functor f, TheorySymbol s)
...
5
votes
2
answers
96
views
Avoid `undefined` when using `TypeError` in type-class constraint
I have a type-class instance like this:
instance {-# OVERLAPPABLE #-} (TypeError ( 'Text "Some error")) => SomeClass x where
someMethod = undefined
This instance exists at the end of ...
10
votes
1
answer
167
views
Is this type-class constraint necessary or redundant?
The following code successfully compiles, but gets a warning when using GHC 9.2.3 with -Wredundant-constraints:
{-# LANGUAGE UndecidableInstances, FlexibleInstances #-}
class Functor f => C f ...
4
votes
1
answer
143
views
How to convey "less than" constraint using type classes?
I am trying to write a version of take that works on length-indexed vectors. This requires the number to take from to be less than or equal to the length of the vector.
This is the current version of ...
6
votes
4
answers
241
views
Superclass constraints vs. instance declarations in Haskell
It kind of seems like in Haskell one can use instance declarations similarly to superclass constraints. I'll give an example using Semigroup and Monoid from Prelude. Here's a simplified definition of ...
1
vote
1
answer
50
views
How do I turn on specialization to eliminate runtime dictionary passing?
While looking at poor runtime performance of some Purescript code I wrote, I noticed that the generated Javascript code contains dictionary passing for overloaded definitions for e.g. transformers ...
4
votes
1
answer
96
views
Is this weaker semialign a known abstraction?
I have a class which looks a lot like SemiAlign, but isn't:
class
( Functor f
)
=> Weakalign f
where
{-# Minimal alignLeft | alignRight #-}
alignLeft :: f a -> f b -> f (...
1
vote
3
answers
137
views
How do you design similar types to enforce particular rules?
Suppose you have a naive vector type, such as
data Vector a
= V2 a a
| V3 a a a
I am interested in how you can — and how you should — implement particular logic specific to the type's constructor....
2
votes
0
answers
67
views
Scala 3: Define a typeclass instance for an inner class
I am trying to define typeclass instances for an inner class.
As a minimal example, I have code that looks like this:
trait Typeclass[T]
class Outer:
class Inner
I would like to define an ...
0
votes
1
answer
24
views
Can I use typeclasses to get non-mixing of subclasses, shared implementation of combine, and also return subclass type?
Cats and Dogs are both Pets, and thus have an age. I would like to define a chooseOldest method that, given either two cats or two dogs, will choose whichever pet is oldest, but which will refuse to ...
2
votes
1
answer
41
views
Instantiate type classes in locale contexts
Suppose I have some locale where a type-class can be inferred from the assumptions.
locale some_locale =
fixes xs :: "'x list"
assumes xs_contains_UNIV: "set xs = UNIV"
begin
...
4
votes
2
answers
132
views
A map of polymorphic values in Haskell
Suppose I've got a class, which declares some constructors for values of its member types:
class C t where
fromInt :: Int -> t
fromString :: String -> t
Further suppose, I want to create a ...
0
votes
1
answer
84
views
Scala 3: Deriving a typeclass for conversion between a case class and a tuple type
I am aware that in Scala 3 it is now possible to convert between case class instances and tuples using Tuple.fromProductTyped and summon[Mirror.Of].fromProduct.
I would like to be able to define a ...
0
votes
2
answers
89
views
Putting a type in the Read typeclass doesn't work in the REPL
I'm defining a type GosperInteger, representing the Eisenstein integers in a complex base, and I'd like to enter these numbers in the REPL and do operations on them. So I put the type in the Read and ...
1
vote
1
answer
84
views
can't use pattern matching with datatypes defined using GADT in haskell
I'm trying to define a Complex datatype, and I want the constructors to be able to take any number as instance, so I would like to use a generic type as long as it does implement a Num instance
I'm ...
0
votes
2
answers
53
views
How to implement subtype resolution of typeclass in scala
I want to understand how to go about implementing the following use-case using typeclasses in Scala (or find out if it is even possible).
Given a sealed trait and a couple of concrete cases:
sealed ...
0
votes
0
answers
26
views
Create a check_html function
def check_html(html_string):
"""Validates an HTML string (text)
Arguments:
html_string (string): the HTML string with tags in each line (separated by \n)
...
0
votes
1
answer
80
views
How to only implement part of the parameters of the MultiParamTypeClasses
How to write Haskell code like (with language extension GADTs and MultiParamTypeClasses):
class MyClass f a where
func :: a -> f a
data MyData a where
Cons1 :: a -> MyData a
...
2
votes
0
answers
151
views
How can I make typeclass about convertibility?
class Convertible a b where
convert :: a -> b
instance {-# OVERLAPPABLE #-} (Convertible a b, Convertible b c) => Convertible a c where
convert = convert . convert -- this ...
1
vote
3
answers
96
views
What is an empty constraint useful for?
In Haskell it is absolutely legal to write
f :: () => Int -> Int
Or even
f :: (Num i, ()) => i -> i
Why is this () allowed? To me it looks like it brought no information, but since it is ...
0
votes
1
answer
62
views
how to universally quantify Reified Type Class instance when scraping your type class in haskell?
Studying the infamous blog post scrap your type classes, for the sake of learning, but in particular to understand the meaning of forall in type class instance declaration as stated here Explicit ...
0
votes
0
answers
71
views
SwiftUI View Protocol in Haskell
I am trying to implement a Haskell counterpart of the View protocol of SwiftUI using type class and type family.
The View protocol in SwiftUI is something like:
protocol View {
associatedtype Body: ...
4
votes
0
answers
119
views
Combine inductive typeclasses
I have a permutation types with has a fixed sizes. Now permutations form a group so I would like to make them an instance of a Group class. Semigroup is easy enough:
instance
( Integral i
)
=...
1
vote
0
answers
87
views
Reversing / enriching typeclass resolution in haskell
Is there any trick to get the "ancestor" proof of a typeclass instance ?
data Dict c = c => Dict
newtype Prod a b = MkProd {getProd :: (a, b)}
class Mk a where mk :: a
instance (Mk a, ...
0
votes
0
answers
88
views
When to use type classes vs traits
When modeling a domain using types, in which situations do traits or type classes have a clear advantage over the other?
In other words: which relationships or constraints cannot be (fully) expressed/...
1
vote
0
answers
59
views
How to propagate type-class evidence through the method chain
I have the following skeleton of the SMap[K] data structure where I want to have special Entry[K] type for the specialized key.
I was following the approach of using the Factory type-class to create ...
5
votes
1
answer
143
views
Algebras for types
One can define a functor on kinds, using "data kind promotion"
data Product m = E| I m | P (Product m, Product m)
It maps a kind m to the sum kind Product m which has 3 types, the empty ...
2
votes
1
answer
80
views
Cartesian product of contraints
Using a lifted version of (,) for the cartesian product of constraint seems to work until you want to use the fact that it's cartesian, which GHC seems unaware of.
GHC seems to treat '(,) as just an ...
2
votes
3
answers
137
views
Looking for a typeclass where category objects are partially consumable (chemical engineering)
Question
I'm looking to describe processes in chemical engineering that that transmute some substances into others. Is there a category that describes morphisms that consume "substances"?
...
6
votes
1
answer
132
views
How was the minimal complete definition Ord chosen?
Data.Ord includes these methods:
compare :: a -> a -> Ordering
(<) :: a -> a -> Bool
(<=) :: a -> a -> Bool
(>) :: a -> a -> Bool
(>=) :: a -> a -> Bool
...
4
votes
3
answers
85
views
What instance of `Num` is used with literals e.g. in `print 1`?
I've just used haskell as calculator expecting to get some cryptic error message about ambiguity of the type instance of the numeric literal. But got none.
For example in ghci
> :t 1
1 :: Num p =&...
2
votes
1
answer
56
views
Having to open quantified type class evidence manually?
Does one have to manually open the evidence like in prj' or is there a more direct way to guide the instance solver ?
{-# LANGUAGE QuantifiedConstraints #-}
{-# LANGUAGE UndecidableInstances #-}
...
2
votes
0
answers
67
views
Composite typeclasses in Haskell
Is there any practical difference between
class (From a b, To a b) => IsomorphismFromTo a b
instance (From a b, To a b) => IsomorphismFromTo a b
and
type IsomorphismFromTo a b = (From a b, To ...
1
vote
0
answers
53
views
Value instance is not a member of cats.kernel.Semigroup
I was trying to create a new type class instance of Semigroup in Cats 2.7.0 for a case class called Expense. The problem occurs when the compiler throws an error telling me that the value instance ...
4
votes
0
answers
138
views
Are Haskell type classes the same thing as Predicate Functor Logic?
I can't find anything connecting Quine's Predicate Functor Logic to Computer Science in general.
But I'm somehow convinced type classes are essentially an encoding of predicate functors, especially ...
1
vote
1
answer
148
views
How to use literal haskell functions in DSL?
I'd like to use literal haskell functions in a dsl as follows:
program :: forall m . DSL m => m ()
program = do
stm $ Stm (Var "a")
-- this way:
f <- fun $ \(a :: Expr a) (b :: ...
8
votes
1
answer
157
views
Can a polymorphic constant be mapped over a list of *types*?
Haskell hobbyist here - is it possible to map a polymorphic constant over a list of types in a generic way?
More precisely, consider this snippet:
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ...
5
votes
2
answers
145
views
When is Ap's Num instance lawful?
Consider this type:
newtype Ap f a = Ap (f a)
instance (Applicative f, Num a) => Num (Ap f a) where
(+) = liftA2 (+)
(*) = liftA2 (*)
negate = fmap negate
fromInteger = ...
5
votes
1
answer
75
views
Instance inductivity as constraint
I'm trying to express an idea that given
instance (MonadTrans t, MonadX m) => MonadX (t m)
it should follow, that any t1 (t2 ... (tn m)) is also MonadX as long as all tx have MonadTrans instance. ...
1
vote
2
answers
96
views
creating instances of classes haskell
So I have this class:
class Collection c where
empty :: c key value
singleton :: key -> value -> c key value
insert :: Ord key => key -> value -> c key value -> c key ...
0
votes
1
answer
58
views
Why does this need both (Eq t, Num t) as type classes? [duplicate]
So I am doing some exercised in Haskell and I thought the type of int2nat in
int2nat :: (Eq t, Num t) => t -> Nat
int2nat 0 = Zero
int2nat n = Succ (int2nat (n-1)
would be int2nat :: (Num t) =&...
3
votes
2
answers
173
views
Is there a map accumulate for things that aren't foldable?
Let's say I have a binary tree:
data BinTree a
= Nil
| Branch a (BinTree a) (BinTree a)
I'd like to do an accumulate map on a structure like this:
mapAccum ::
(
)
=> (a -> b -> (...
0
votes
0
answers
49
views
Return concrete type for a trait from it's companion object
Previously I returned concrete types from a trait, but never from a companion object of a trait and couldn't find an example of my exact scenario online. Please feel free to point me if this is a ...
0
votes
1
answer
68
views
Cannot represent equality constraint as a custom constraint
I have a function type declaration
f :: MonadHandler m => SqlPersistT m ()
Which I want to convert to
f :: MonadHandlerDB m => m ()
I try everything I can think of to define constraint ...
2
votes
1
answer
74
views
What's the point of instances polymorphic only on type constructors?
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
In Haskell I can do something like
class C a where
c :: a -> a
instance C (f Integer) where
c = id
As seen, the instance of C is ...