I’m trying to write a substitution algorithm in Haskell.
I have defined a polymorphic data type Subst a with a single constructor S::[(String, a)] -> Subst a as so:
data Subst a = S [(String, a)]
I now want to write a function single::String -> a -> Subst a for constructing a substitution for only a single variable
This is what I tried:
single::String -> a -> Subst a
single s1 (Subst a) = s1 a
However, I’m getting this error: Not in scope: data constructor 'Subst'
Does anyone have insight to what i’m doing wrong?
The data constructor is not the same thing as the type constuctor
In your code the type constructor is
Substthe data constructor isSType constructors are used to create new types, e.g. in
data Foo = Foo (Maybe Int)Maybeis a type constructor,Foois the data constructor (as well as the type constructor, but they can be named differently as you discovered). Data constructors are used to create instances of types (also don’t confuse this with creating an instance of a polymorphic type, e.g.Int -> Intis an instance ofa -> a).So you need to use
Swhen you want to pattern match in yoursinglefunction. NotSubst.Hopefully that makes sense, if not, please tell me 🙂
P.S. data constructors are, for all intents and purposes, functions, which means you can do the same things with them that you’d typically do with functions. E.g. you can do
map Bar [a,b,c]and it will apply the data constructor to each element.