简体   繁体   中英

Making a type polymorphic

So i'm defining a type which a list of tuples basically and I can't work out how to make it polymorphic. so far i've got

module ListTup where
type ListTup = [(Char, String)]

and I was wondering if it was possible to make it so that the Char part could be anything ei String, int what ever. Is it possible? I tried to use the Maybe Type but it throw a ton of errors my way

You can include type variables when defining type synonyms, like so:

type ListTup a = [(a, String)] .

It depends on what you want to do. If you want different lists each of which will have the same type in the tuple's first element, you can parametrise the type constructor, like C.Quilley suggested above.

If you want each of your lists to be able to have different types, you can box all required types in an algebraic type (discriminated union):

data MyKey = MyCharKey Char | MyStringKey String | MyIntKey Int
type ListTup = [(MyKey, String)]

You cannot have "whatever", because the types need to be decidable at compilation time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM