Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define different behaviour for generic types depending on which typeclasses are implemented?

Tags:

haskell

There is actually an extra layer to what I'm trying to ask, but the wording is a bit awkward. Here's an example using the YesNo typeclass from "Learn You a Haskell".

class YesNo a where
    yesno :: a -> Bool

instance YesNo Bool where
    yesno = id

instance YesNo [a] where
    yesno lst = length lst > 0

Here, the generic type is [a]. Could this code be changed so that yesno uses different logic (e.g. returns False) when a implements YesNo?

like image 643
Zantier Avatar asked Aug 04 '14 00:08

Zantier


People also ask

What is the difference between generic class and int type?

If we want the data to be of int type, the T can be replaced with Integer, and similarly for String, Character, Float, or any user-defined type. The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section.

What is a generic class in Java?

Generics in Java. Generics mean parameterized types. The idea is to allow type (Integer, String, … etc, and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a ...

How to restrict the types allowed for a generic type?

In MyGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions. Consider the example class below: In declaration of the class, we specified a constraint “T extends Number”.

Is it possible to write a type safe class using generics?

Instead of asking to write Generic method Interviewer may ask to write a type safe class using generics. again key is instead of using raw types you need to used generic types and always use standard place holder used in JDK. Q6. What is bounded type parameter?


1 Answers

The typical, and usually best, thing to do when you have a need for type classes to behave differently based on a contained element is to actually make a newtype wrapper and manually wrap the list up at the call site.

The newtype declarations would look like:

newtype AllOf a = AllOf { unAllOf :: [a] }

newtype AnyOf a = AnyOf { unAnyOf :: [a] }

And, unsurprisingly, the instances use all or any on the underlying list:

instance YesNo a => YesNo (AllOf a) where
    yesno = all yesno . unAllOf


instance YesNo a => YesNo (AnyOf a) where
    yesno = any yesno . unAnyOf

Then when you want to use the instance:

*Main> yesno (AllOf [True, True, False, True])
False
*Main> yesno (AnyOf [True, True, False, True])
True
like image 64
Thomas M. DuBuisson Avatar answered Nov 06 '22 18:11

Thomas M. DuBuisson