[Checkpointing John Goerzen **20070801051930] { hunk ./en/ch13-data.xml 12 + + + Back in FIXME: add ref to chapter 3ish, you saw how to + use &type; to create handy aliases for types. That's a useful feature, + but in this chapter we'll take it a step further. We'll show you how to + create entirely new types. After doing that, we'll also show you some of + the built-in tools that Haskell provides for arranging large amounts of + data. + + + + Basic Type Creation + + To create a new type, we use the &data; keyword. In its most simple, + though probably useless, form, you can create a type like this: + + &data1.hs:useless; + + This defines a new type called Silly. There is one + type constructor for Silly: + Foo. When you write Foo in your + program, this Foo is a value of type + Silly. You can actually use the same word for both, + but it must start with an uppercase letter. + + + Looking at it with &ghci;, there's not much you can do with it yet: + + &data1.ghci:useless; + + Note that &ghci; doesn't know how to display Foo to + the screen, or how to compare it to itself. That's because we haven't + made our new type a member of the &Show; and &Eq; typeclasses. We'll + make a new example that is a member of these classes, and then we'll + get more information out of &ghci;. For more on typeclasses, refer to + . + + &data1.hs:silly2; + + We've also defined a function that takes any parameter and returns + a value of type Silly2. Let's play with this in + &ghci;. + + &data1.ghci:useless2; + + You can see here how the types interact. Let's now expand on this + foundation with some more things that can be done with &data;. + + + + + + addfile ./examples/ch13/data1.ghci hunk ./examples/ch13/data1.ghci 1 +--# useless +:l data1.hs +:t Foo +Foo +Foo == Foo + +--# useless2 +:t Foo2 +Foo2 +Foo2 == Foo2 +Foo2 == Foo +:t toSilly2 +:t toSilly2 5 +toSilly2 5 hunk ./examples/ch13/data1.hs 1 +{-- snippet useless --} +data Silly = Foo +{-- /snippet useless --} + +{-- snippet silly2 --} +data Silly2 = Foo2 + deriving (Eq, Read, Show) + +toSilly2 :: a -> Silly2 +toSilly2 _ = Foo2 +{-- /snippet silly2 --} + + }