Try   HackMD

Drill 10 Solution

Question 1

For this and the next several questions, we'll use a position datatype
defined as follows:

data Posn:
  | posn(x :: Number, y :: Number)
end

Write an expression that constructs a position with an x-value of 2 and a y-value of 29.

Answer

posn(2,29)

To create a data value of type Posn, use the posn constructor that takes in 2 numbers for its x and y values.

Question 2

Assume we've defined the Posn data-type, as above, and we've defined a Posn named p.

Write an expression that evaluates to the x-value of p.

Answer

p.x

Use the . operator in order to access the values of a given data construct.

Question 3

Assume we've defined the Posn data-type, as above, and we've defined a Posn named p.

Write an expression that constructs a new position with each coordinate of p doubled.

Answer

posn(2 * p.x, 2 * p.y)

We use the posn constructor, passing in 2 * the x and y coordinates of p.

Question 4

Given this data type Student and value with name jeff:

data Student:
  | student(id :: String, major :: String, GPA :: Number)
end

jeff = student("B00", "CS", 3.5)

Which expression creates a new value, jeff-updated, with a GPA of 4.0?

( ) jeff-updated = jeff.GPA + .05
( ) jeff-updated = Student(jeff.id, jeff.major, 4.0)
( ) jeff-updated = student(jeff.id, jeff.major, 4.0)
( ) jeff-updated = jeff.GPA.4.0

Answer

( ) jeff-updated = jeff.GPA + .05
( ) jeff-updated = Student(jeff.id, jeff.major, 4.0)
(X) jeff-updated = student(jeff.id, jeff.major, 4.0)
( ) jeff-updated = jeff.GPA.4.0

Use the student constructor in order to make a new value of type Student.

Question 5

Fill in the blanks to create the data-type Three-D-Posn with coordinates x, y, and z.

[Blank1] Three-D-Posn:
   | posn3d(x :: Number, y :: Number, [Blank2])
[Blank3]
Answer

Blank1: data

The definition of any datatype begins with the keyword data.

Blank2: z :: Number

We need the third coordinate z, and like the others, it is of type Number.

Blank3: end

Datatype definitions need to end with end, just like a function or if expression.