Haskell type declarations

In Haskell, why this compiles:

splice :: String -> String -> String
splice a b = a ++ b
main = print (splice "hi" "ya")

but this is not so:

splice :: (String a) => a -> a -> a
splice a b = a ++ b
main = print (splice "hi" "ya")

>> Type constructor `String' used as a class

I would think that this is one and the same. Is there a way to use a second style that avoids repeating a type name 3 times?

+3
source share
5 answers

Type syntax =>for typeclasses .

When you say f :: (Something a) => a, you do not say what ais Something, you say that it is a type of "in group" Something.

For example, Numis a class that includes types such as Intand Float. However, there is no type Num, so I can’t say

f :: Num -> Num
f x = x + 5

However i could say

f :: Int -> Int
f x = x + 5

or

f :: (Num a) => a -> a
f x = x + 5
+13
source

Actually, this is possible:

Prelude> :set -XTypeFamilies
Prelude> let splice :: (a~String) => a->a->a; splice a b = a++b
Prelude> :t splice
splice :: String -> String -> String

~. , , String -> String -> String, , .

+3

, 3 ?

. ,

type S = String
splice :: S -> S -> S

-

type BinOp a = a -> a -> a
splice :: BinOp String

, - , String -> String -> String, . , , .

splice :: [a] -> [a] -> [a]

, .

+3

... String - , .

splice, :

import Data.Monoid

splice :: Monoid a=> a -> a -> a
splice = mappend

EDIT: so the syntax here is that the top-level words left to the left =>are class classes that bound the variables that appear to the right of =>. All upper words on the right are type names

+1
source

You can find explanations in this "Learn You a Haskell " section .

+1
source

All Articles