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,949
questions
9
votes
0
answers
128
views
How unsafe is coercing typeclass dictionaries?
I've got situation where I had a product type (say T), and an instance of say C derived using anyclass deriving, which works because each member of T is an instance of C.
I changed one member of T to ...
1
vote
0
answers
113
views
Haskell data vs class
I've written an LALR1 parser which seems to work. It can be parameterised for the type of symbols it receives. The only binding is Eq.
module LALR.Parser where
data Rule symbolT = Rule
{
...
1
vote
3
answers
94
views
Expressing multi-parameter typeclasses in terms of single-parameter ones
For a certain reason (weird Hugs installation on target computer) I want Haskell98 compliant code, which means no common language extensions. One annoyance in particular is the absence of multi-...
2
votes
1
answer
48
views
Caching an expensive to compute result in a class instance
Lets say I've got something like the following
class C a where
f :: a -> Text
newtype T a = T a
expensiveFunction :: (Bounded a, Enum a, ToText a) => Map a Text
expensiveFunction = _
...
1
vote
2
answers
55
views
Selecting a named implementation in Idris 2
According to this old answer, Idris 1 has the using syntax to select default implementations for a block of code. What is the corresponding Idris 2 syntax?
I've tried using the syntax from the answer:
...
0
votes
1
answer
43
views
Expressing a typeclass with associated types and constants?
I'm trying to work out how to implement the concepts of associated types and constants for a typeclass in Haskell.
As practice, I am trying to make a typeclass for A* nodes. A node has the given ...
0
votes
0
answers
42
views
How derives works with value classes in Scala3?
I have a value class ItemId and I want to take advantage of derives for JsonCodec
I would like to do something like this:
final case class ItemId(value: Long) extends AnyVal derives JsonCodec
...
2
votes
1
answer
119
views
Can you not to export an instance in Haskell?
Yeah, I know this sounds unreasonable. Guess there are better approaches than simply hiding an instance.
I'm working on a library about images. Inside one module, there is an enum type for the sizes ...
1
vote
0
answers
160
views
Which kinds of lawfull `Functor`s are possible in Haskell?
I know following types of Functors:
Polynomial functor == simple not-nested parameterized datatype
Generalization of 1, by using "parameter removing" newtypes: Fix, Some (existentials), ...
1
vote
2
answers
117
views
Why include (Eq t) in the signature for t -> [t] -> [t] when working with Haskell lists?
I am working with functions that use lists of type t elements. It means that the list can be a list of integers or a list of strings or characters. But i can't get why (Eq t) has to be in the type ...
0
votes
1
answer
112
views
In scala property based tests for tagless final with variable inerpreter
I have the following algebra
// domain
case class User(id: String, name: String, age: Int)
// algebra
trait UserRepositoryAlgebra[F[_]] {
def createUser(user: User): F[Unit]
def getUser(userId: ...
0
votes
1
answer
89
views
No implicit Ordering defined for ord
I want to define a collection class and require its element being Ordered
Considering the code below:
class MyCollection[K: Ordered[K]] {
def func(seq: Seq[K]): Unit = {
seq.sorted
}
}
The ...
2
votes
1
answer
169
views
Tuples in Scala 3 Compiler Operations for Typeclass Derivation
Learning some of the new Scala 3 comppiletime operations and a bit confused about Tuple ( particularly using type matching on *: and EmptyTuple)
import scala.compiletime.*
imort cats.Show
transparent ...
3
votes
2
answers
286
views
In Scala 2 or 3, is there a higher kind argument extractor without using match type?
Here is a short example in Scala 3:
type Ext[S <: Seq[_]] = S match {
case Seq[t] => t
}
trait XX[A, B <: Seq[A]]
trait XX1[B <: Seq[_]] extends XX[Ext[B], B]
So far it ...
2
votes
1
answer
111
views
Scala: implicit type transformation with condition on value
The task is to perform transformation from string value to Int or BigDecimal, depends on string value length.
For example, if stringValue > 10 => stringValue.toInt, else => BigDecimal(...
6
votes
2
answers
252
views
Is it possible to disambiguate instances with an intermediate step?
Suppose a scenario where you have an application config, the structure of which has changed a few times. To provide ease of use for users, you wish to allow automatic migration from each version to ...
3
votes
2
answers
140
views
Can't code my component in a tagless-final way / using type classes and instances
(This is the concrete case behind How do I conditionally declare an instance?)
In my small project players can create/join/watch a game session or list the ongoing sessions. A very simple Yesod app ...
4
votes
3
answers
201
views
How do I conditionally declare an instance?
How do I say an instance of B could be made for those m s that are instances of A but say nothing about other m s:
-- A.hs
module A where
class A m -- m :: * -> *
-- B.hs, totally unrelated to A
...
1
vote
3
answers
104
views
Why can't I return a concrete type in a function that has a polymorphic return type?
For example, why isn't it possible to define a function like -
fun::a
fun = 1
-- OR
someInt::Int
someInt = 3
fun::Num a => a
fun = someInt
It seems like this is possible in Java -
class App {
...
1
vote
2
answers
55
views
Dynamically overriding typeclass methods
Suppose I have a data type T that has an equality function and a list:
data T a = T (a -> a -> Bool) [a]
How can I use a predefined function that requires Eq a, but uses the equality function ...
0
votes
1
answer
43
views
Correct way to specify inline implicit ordering
Let's say I've got a case class definition:
// Scala 2.13
case class Employee(name: String, id: Int)
Then I'd like to specify an inline implicit ordering like:
es.sorted(implicit ord: Ordering[...
1
vote
1
answer
126
views
Shapeless - How to derive LabelledGeneric for Coproduct
I'm trying to generate LabelledGeneric for Coproduct, so that it can be used instead of typical sealed trait hierarchy. So far I was able to do it by explicit specification of labels for ...
0
votes
1
answer
74
views
How can I implement Fractional[Int] and get access to new arithmetic operations
I am trying to create a Fractional[Int] instance in Scala 3 that I want to use for finite field arithmetic.
I have a class whose instances can work as Fractional[Int] implementations:
class IntModp(...
3
votes
2
answers
107
views
How to implement `Constraint` reflection? [Ad-Hoc polymorphism based on available Constraints]
For example, with types, you can implement AdHoc polymorphism using Typeable to define a different behavior depending on what the input type is:
foo :: forall a. Typeable a => a -> a
foo | Just ...
0
votes
1
answer
125
views
How to write an implicit Numeric for a tuple
I have a scenario where I would like to call sum on a sequence of (Double, Double) tuples.
Ideally I would like to do something like the following:
implicit def toTupleNumeric[T](num: Numeric[T]) = ...
1
vote
1
answer
83
views
Creating an instance without requiring a newtype dummy
Lets say I have the following:
class C a where
f :: a -> Blah
f_impl_for_d :: D a => a -> Blah
f_impl_for_d = _
newtype Alice f a = Alice (f a)
And maybe some existing instances like ...
0
votes
2
answers
169
views
Scala how to derivate a type class on a trait
In the following example I would like to be capable to use an implicit type class - Process - wit a trait as input. But the compilator does not recognize any implicit in that case. I was expecting as ...
0
votes
2
answers
139
views
Ad-hoc Polymorphism vs. Data Constructors in Haskell
Defining different data constructors for a type, and then defining functions using pattern matching over them resembles ad-hoc polymorphism in other languages a lot:
data Shape = Circle Float | ...
10
votes
4
answers
291
views
Take action based on a type parameter's typeclass?
I suspect I have a fundamental misunderstanding to be corrected, so will start with the general concept and then zoom in on the particular instance that lead me to think this way.
Generally speaking, ...
1
vote
1
answer
80
views
Trying to impliment something similar to type classes in C++ but getting a segfault
#include <iostream>
using namespace std;
template <typename T>
class ISignalFilter;
template <typename F>
class ProductFilter;
template <typename T>
class ISignalFilter {
...
0
votes
1
answer
81
views
Suspicious Shadowing by a Type Parameter while defining Scala 3 Type Class
I'm trying to implement some small quality-of-life improvements around an XML parser, basically trying to ape the way Circe looks like for Json parsing in Scala.
The idea then would be to come up with ...
0
votes
2
answers
153
views
correct setup for opaque type with underlying Numeric/Ordering instances
unclear to me if this is in fact the same question as here or here, apologies if this is a duplicate.
i would like to define a type Ordinate which is simply an Int under-the-hood:
package world
...
2
votes
2
answers
99
views
How to define a superclass constraint for free monoids?
Consider the following type class for free monoids.
class FreeMonoid f where
inj :: a -> f a
univ :: Monoid m => (a -> m) -> f a -> m
inj injects a value into the free monoid, ...
1
vote
1
answer
123
views
Why is my Semigroup/Monoid instance overlapping?
I'm trying to implement a way to lazily construct nondeterministic finite automata (NFAs). I did this years ago in F# and now want to try it with Haskell while leveraging the Monoid typeclass.
{-# ...
2
votes
0
answers
89
views
Is it possible to see to see all the classes a typeclass is related to? Or at least its subclasses?
I find it very informative and useful to see which instances a class has. It helps me understand what a class is used for and how. Thankfully this information is available both in GHCi (through the :...
0
votes
1
answer
157
views
Scala implicit class based on type class
implicit class IntIncrement(val underlying: Int) extends AnyVal {
def increment(): Int = underlying + 1
}
This is valid and allows me to do something like 1.increment()
I want to be able to ...
1
vote
1
answer
37
views
Returning functions that check for equality/ordinal comparison for any valid type parameter
I'm not very experienced with using Scala and I think I'm missing something when it comes to implicits. I'm essentially trying to take an enumerated argument that represents a certain logical operator ...
0
votes
1
answer
144
views
how do you do recursion with type classes and data type in Haskell?
I am working on a type class for fraction, vector, and matrix arithmetic (ie add, sub, mul) but can't quite get the vector instance because I don't know how to work with the recursive nature of the ...
0
votes
1
answer
160
views
Adding type class to the function defenition doesn't help in Haskell
In the line
eval :: (Enum Instruction) => [Instruction] -> [Value] -> [Value]
eval inst mem = evalSecond (evalStep ((fromList Halt inst), (fromList 0 mem), (0,0,0,0), (ZeroFlag, EvenFlag)))
...
0
votes
1
answer
115
views
Scala Trait Returning a Sub-type?
Given a trait:
@ trait Foo {
def withStuffAdded(str: String): Foo
}
defined trait Foo
I then defined a sub-class of Foo:
@ class X(val str: String) extends Foo {
override def ...
6
votes
1
answer
182
views
Is it possible to use type synonyms to hide type variables when declaring instances?
I have this typeclass:
class Monad m => Convertible m a b where
convert :: a -> m b
For many pairs of types, the conversion can be done purely, without requiring a monadic effect.
Now, I know ...
1
vote
2
answers
101
views
Type system troubles: RankNTypes + Typeclasses
I've been having some troubles with combining typeclasses with higher-rank types in haskell.
The project I'm working on is an interpreter based around an evaluation monad. I'm currently attempting to ...
2
votes
1
answer
59
views
Matching on a particular type of a parametric type
I'm trying to work with an external library that has provided a parametric type like this:
data ParametricType a = TypeConstructor a
I have a typeclass, something like this:
class GetsString a where
...
4
votes
3
answers
307
views
Selecting a type-class instance based on the context (once again)
Ok this topic had been discussed a lot of times, but since Haskell evolves lets consider it again to see what we can do in contemporary Haskell (by contemporary I mean GHC 9.0 - 9.2).
Fist let me ...
0
votes
1
answer
97
views
What does `import ev._` for implicit evidence mean, and when should I use it?
the Arithmetic.scala is:
package Arithmetic
// The Arithmetic typeclass which implements various arithmetic operations on custom datatypes
abstract class Arithmetic[T <: Data] {
implicit def cast(...
1
vote
1
answer
116
views
How to derive a Generic.Aux if the case class has a type parameter - Shapeless
given:
sealed trait Data
final case class Foo() extends Data
final case class Bar() extends Data
final case class TimestampedData[A <: Data](data: A, timestamp: Long)
Is there a succint way to ...
0
votes
1
answer
173
views
Scala 2.13: Case class with extendable variable attributes?
I want to create a case class which can incorporate a record of string and another case class entity.
For example:
case class Student(
name: String
age: Int
)
case class Example(
[key:String]: Student
...
0
votes
1
answer
154
views
The Writer monad and its type declaration
I am trying to get a better understanding of Monads and I am currently looking into the Write Monad in http://learnyouahaskell.com/for-a-few-monads-more#writer
I don't understand its type declaration ...
2
votes
1
answer
238
views
Shapeless3 and annotations
This is a followup on Shapeless and annotations. The original question was asked in the context of Scala 2 and Shapeless2.
Some features from Shapeless2 were migrated to Shapeless3, such as ...
0
votes
1
answer
88
views
Can I always replace do ... pure ... with ado ... in ... in Purescript?
Can I always replace a do-block like this:
do
...
pure ...
where the last line is "pure" something,
with an ado-block like this:
ado
...
in ...
?
I know do only requires Bind and ...