Search code examples
haskellalgebraic-data-typesgadt

Data type without input value and multiple primitive types


Firstly, I'd like to apologize if I'm repeating this but I searched everywhere without finding an answer to my question.

Suppose I have the following code:

data TestType = Nothing | Int | Float deriving (Show)

jaykay :: TestType -> [Char]
jaykay Int = "This is an int"
jaykay Float = "This is float!"
jaykay a = "Nothing matched.."

main :: IO()
main = do
  jaykay [PLACE HOLDER]

Clearly this type does not have any value constructor(s). So what I thought I could do here is create a type from primitive types that would normally hold any values of the specified ones in the definition right? My question is about how would I construct an instance of this type and also if this definition isn't correct how would I achieve what I described earlier?

Thanks


Solution

  • Actually, your type does have value constructors -- three of them, in fact, named Nothing, Int, and Float. So, one could write, for example

    main = putStrLn (jaykay Int)
    

    and running the program would print out This is an int. However, I suspect that you wanted your constructors to accept arguments of the related types; so you probably wanted to write something like

    data TestType = Nothing | Int Int | Float Float
    

    so that values of type TestType constructed with the Int constructor would contain an additional value of type Int; and likewise those constructed with the Float constructor would contain a value of type Float. (N.B. there are two separate namespaces here! There is a type-level name Int which comes from the Prelude and you have now also defined a value-level Int whose type is Int -> TestType.)

    An example of using this more exciting new data type would be this:

    jaykay (Int i) = "got the Int " ++ show i
    jaykay (Float f) = "got the Float " ++ show f
    jaykay a = "dunno lol"
    
    main = putStrLn (jaykay (Int 3))
    

    Running this program would print out got the Int 3.