'What is the difference between if and cond?

Perhaps I am misunderstanding something.

In Hy, if* can take (after the if* symbol)

  • one predicate (evaluation returned if there are no further expressions)
  • zero or one consequent (evaluated and returned if the predicate is truthy)
  • (if a consequent exists) zero or one alternative (evaluated and returned if the predicate is falsy)

If the predicate is falsy and no alternative expression is supplied, None is returned.

if (with no star) can handle any number of pairs of predicates and consequents, with a final, optional non-predicate expression being evaluated and returned if no predicates evaluate as truthy.

How is this different to cond, except for cond's need for brackets around predicate-consequent pairs?

hy


Solution 1:[1]

Update

As of #2240 (merged 2 Mar 2022), if and cond are somewhat different from what they used to be, and are better distinguished from each other. if requires exactly three arguments:

(if condition-form
  then-form
  else-form)

cond takes any even number of arguments and doesn't require brackets or provide implicit dos:

(cond
  condition1 then1
  condition2 then2
  condition3 then3)

if* has been removed.

Original answer

The square brackets in cond provide an implicit do. That's it. I typically use if only for two-branch cases and cond for everything else. The existence of if* is really just an implementation detail.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1