Question about nested choice in verse

I’m just watching the Simon Peyton Jones video and he gives this example:

x := (y | 2); y := (7 | 8); (x, y)

And the result is:

(7, 7), (8, 8), (2, 7), (2, 8)

What I don’t understand is why isn’t the result:

(7, 7), (7, 8), (8, 7), (8, 8), (2, 7), (2,8)

I’ve never worked with Haskell so it may be obvious to many, but I’d love an explanation as to how nesting works here.

2 Likes

This doesn’t exist yet, but it’s because each variable can only have one value at a time:

x := (y | 2) # y doesn't exist yet, we'll keep searching
y := (7 | 8) # Now x has a value
(x, y)

(7, 7) # We start with the first value of x and the first value of y, x = y and y = 7, so x = 7 too
(8, 8) # We stick with the first value of x and move to the second value of y, x = y still and now y = 8, so x = 8 as well (since y is always one value)
(2, 7) # The second value of x, and the first value of y
(2, 8) # The second value of x and the second value of y
3 Likes

This video hit my brain hard too, and I agree with you, everything tends to think that we’d compute the values of Y after the values of X here (the expression order, the tuple order)

This video felt a bit scary at the time, maybe just go learn with the courses present in the docs instead if you’re still learning.

I’m glad this is not in the language yet, but maybe I don’t understand this fully either.

1 Like

That example would work like this:

(x, y)
# Solve x and y:
(x1 | x2, y1 | y2)
# Unpack the choices:
(x1, y1), (x1, y2), (x2, y1), (x2, y2)
# Solve x1, y1, x2 and y2:
(y, 7), (y, 8), (2, 7), (2, 8)
# Solve y:
(7 | 8, 7), (7 | 8, 8), (2, 7), (2, 8)
# Unpack the rest of the choices:
(7, 7), (8, 7), (7, 8), (8, 8), (2, 7), (2, 8)

It has more results because y is only used in one place - I explained the last example pretty poorly before (I updated it), but to reiterate:

  • For (x, y), we first evaluate x, which is (y | 2) and needs to be its first option y, then we evaluate y, which also needs to be its first option 7, therefore (x, y) = (7, 7)

  • Then, we move to the second value for y with the same value of x, but since x is currently binded to y, both change - so it’s (8, 8), since y has to equal 8, and so does x since x = y

  • Then we move to the second value of x, which is 2, and use that for both values of y to get (2, 7) and (2, 8)

3 Likes

I know he said this in the video, but repeating this along with your example comments got this to finally click in my head. Thank you so much!

Not sure if “dependency” is the right word here, but it totally makes sense that when you make x depend on y, since y can only have one value, x must take whatever value y is.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.