Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions xml/chapter4/section1/subsection2.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2140,6 +2140,56 @@ list("logical_composition",
as derived components.
</JAVASCRIPT>
</SPLIT>
<SOLUTION>
GitHub user EmilyOng provides a solution for the alternative:
how to implement
<JAVASCRIPTINLINE>&amp;&amp;</JAVASCRIPTINLINE> and
<JAVASCRIPTINLINE>||</JAVASCRIPTINLINE>
as derived components.
<SNIPPET>
<JAVASCRIPT>
function make_conditional_expr_decl(predicate, consequent_expression, alternative_expression) {
return list("conditional_expression", predicate, consequent_expression, alternative_expression);
}
function make_literal(value) {
return list("literal", value);
}

// Syntax selectors
function logical_operation(component) {
return head(tail(component));
}
function first_expression(component) {
return head(tail(tail(component)));
}
function second_expression(component) {
return head(tail(tail(tail(component))));
}

function logical_comp_decl_to_conditional_expr_decl(component) {
const operation = logical_operation(component);

return operation === "&amp;&amp;"
? make_conditional_expr_decl(
first_expression(component),
second_expression(component),
false
)
: operation === "||"
? make_conditional_expr_decl(
first_expression(component),
true,
second_expression(component)
)
: error(component, "unknown operation -- logical_comp_decl_to_conditional_expr_decl");
}

display(logical_comp_decl_to_conditional_expr_decl(parse("a &amp;&amp; b;")));
display(logical_comp_decl_to_conditional_expr_decl(parse("a || b;")));
display(logical_comp_decl_to_conditional_expr_decl(parse("(a &amp;&amp; !b) || (!a &amp;&amp; b);")));
</JAVASCRIPT>
</SNIPPET>
</SOLUTION>
</EXERCISE>

<EXERCISE>
Expand Down