Returning an instance of a class in a Haskell function

If the return of the function is equal class ClassA, is it possible to return any instance to such a function ClassA? Example:someFunction :: (ClassA a) => String -> a

So why does this function below not work? Please note that Stringis an instanceEq

getAnyEq :: (Eq a) => String -> a
getAnyEq input  |input == "1" = "something"
                |otherwise = "other"

An error has occurred:

Could not deduce (a ~ [Char])
from the context (Eq a)
  bound by the type signature for getAnyEq :: Eq a => String -> a
  at src/InterceptorRegistry.hs:11:13-33
  `a' is a rigid type variable bound by
      the type signature for getAnyEq :: Eq a => String -> a
      at src/InterceptorRegistry.hs:11:13

I tried to find this exact explanation in Internet resources, but I did not find ... could you show me?

+4
source share
3 answers

Type Eq a => adoes not mean "Type that implements Eq", but "Any type that implements Eq. For example, if you implement your function using undefined:

getAnyEq :: (Eq a) => String -> a
getAnyEq str = undefined

( undefined ):

x,y,z :: Bool
x = getAnyEq "test" == "hello"
y = getAnyEq "test" == [Just (Right True)]
z = getAnyEq "test" == ("this", "sss")

, .

, , , , , . , Num:

class (Eq a, Show a) => Num a where
  (+) :: a -> a -> a
  (*) :: a -> a -> a
  (-) :: a -> a -> a
  negate :: a -> a
  abs :: a -> a
  signum :: a -> a
  fromInteger :: Integer -> a

( , ghc, Num Eq Show).

fromInteger a ( a), a . , . , :

getANum:: (Num a) => String -> a
getANum "zero" = fromInteger 0
getANum "asdf" = fromInteger 46
getANum _ = fromInteger 1

> getANum "asdf"
46

, fromInteger <num>, fromInteger, , . , , .

, , :

  • Monad ( return)
  • Applicative ( pure)
  • Monoid ( mempty)
  • Read ( Read )
+11

@David Miani, , Haskell forall ( ∀):

getAnyEq :: (Eq a) => String -> a

getAnyEq :: forall a . (Eq a) => String -> a

{-# LANGUAGE ExplicitForall #-}. , a, Eq, getAnyEq . ( String), forall.

, , ∃:

getAnyEq :: exists a . (Eq a) => String -> a

GHC, , , UHC (Utrecht Haskell Compiler) . , .

+3

, , , - . , getAnyEq:

{-# LANGUAGE ExistentialQuantification #-}
data ShowEq = forall s. Eq s => SE s 

getAnyEq :: String -> ShowEq
getAnyEq input  |input == "1" = SE "ds"
                |otherwise = SE "ss"

, : http://en.wikibooks.org/wiki/Haskell/Existentially_quantified_types

+1

Source: https://habr.com/ru/post/1529694/


All Articles