Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell 'let' implementation

Tags:

haskell

happy

Reading Haskell.Happy documentation and reached the implementation of 'let' operator

 Exp : let var '=' Exp in Exp              { \p -> $6 (($2,$4 p):p) }

docs say it's "a function that takes an environment of variable values, and returns the computed value of the expression:"

can't understand the actual meaning of the syntax, how are these constructions called in Haskell?

Edit: i mean these

\p -> $6 (($2,$4 p):p)
like image 756
Herokiller Avatar asked Jan 31 '26 14:01

Herokiller


1 Answers

A let expression in ML-like languages (such as Haskell) just introduces a local variable binding:

magnitude x y =
  let xs = x * x in
  let ys = y * y in
  sqrt (xs + ys)

The Happy docs are talking about implementing a parser for a hypothetical ML-like language. The $n variables in Happy syntax refer to the indices of the things that matched in the current rule:

let var '=' Exp in Exp
1   2   3   4   5  6

The expression in the curly braces is the code to generate when that rule matches.

So \p -> $6 (($2,$4 p):p) gives you a lambda which takes a variable environment p, which is a list of pairs of names and values. The body of the lambda consists of the second expression parsed ($6) evaluated in p, plus the association between the name ($2) and the value resulting from evaluating the first expression parsed ($4) in the current environment ($4 p).

like image 129
Jon Purdy Avatar answered Feb 02 '26 07:02

Jon Purdy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!