Basic Data Constructors in PureScript

Vincent Orr
InstructorVincent Orr

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 4 months ago

PureScript types are very extensive and we are going to experiment with type constructors and how to make then use them.

Instructor: [00:00] Let's make our data constructor with the keyword, data. Foo equals foo, pipe, then bar, and string. This is saying we have a data constructor of foo, and it has two types of foo and bar, which expects a string.

[00:14] Let's make a function runFoo, with the types of foo to string. Now, we're going to do a bit of pattern matching. On the next line, runFoo foo equals a string of, "Damn right, it's foo." If we look to the right, we have an error.

[00:28] What it's saying is that all the cases in the foo constructor haven't been covered. We've done runFoo foo. Now, we also need to do runFoo bar, S for the string. Then that equals, "Yeah, and it's bar," and the symbols less than, greater than S.

[00:44] Those two symbols represent string concatenation. In JavaScript, the equivalent would be ++. Looking at runFoo, bar, S, we know that we expect our S to be a string. We're just concatenating two strings, which will be, "Yeah, it's bad," and whatever the string that we pass in.

[00:59] Let's see this in action by typing runFoo, foo. As you can see, it outputs, "Damn right, it's foo." If we look at runFoo, it did a pattern match on foo, and gave us back the string, "Damn right, it's foo." Let me explain something.

[01:11] It might be a little bit confusing when we look at data foo equals foo, then bar, string. What we'll do is we'll change the second value to foo one. On line 10, we'll change foo one there. Now, you can see that on line nine, we have runFoo, which uses a data constructor of foo, which tells us that we need to pattern match against foo on and bar.

[01:33] Let's test this out. We'll go to runFoo, and we will change it to bracket, bar, and then the string, "His buddy." I'll runFoo function pattern matches on the bar, and it takes the S as, "His buddy." It concatenates S, which is, "His buddy." It's, "Yeah, it's bar and his buddy."

[01:52] It should be added that if you were to do runFoo, bar, and then say one, the compiler would fail with a type error, because it is expecting a string. There you have it, some basic data constructors in PureScript.

~ 5 years ago

You say that string concatenation in JavaScript is ++ in fact it's just +. I think you're thinking of Haskell, which of course PureScript is based on.

Vincent Orr
Vincent Orrinstructor
~ 5 years ago

@Simon you're absolutely right! good spot :facepalm: