4

I got the impression from the manual that

    | a |   |
    | b |   |
    #+TBLFM: $2=if($-1==a, 1, 0)

should produce "1" in the first row and "0" in the second. But instead I get

    | a |             1 |
    | b | b = a ? 1 : 0 |
    #+TBLFM: $2=if($-1==a, 1, 0)

What am I misunderstanding here?

Will Brown
  • 41
  • 1

2 Answers2

4

You are probably better off using Lisp formulas for things like this. As @db48x's answer points out, there are a couple of cooks in that kitchen and what they are doing is not always obvious. Formula debugging can help but it is not always effective (I presume that's how @db48x discovered the "(a)" thing, but that may not be the case).

I find the string conversions unpredictable, so for non-numeric things in particular, I tend to stay away from calc formulas and do it in Lisp instead.

In this particular case, try the following:

| a | 1 |
| b | 0 |
#+TBLFM: $2 = '(if (string= $-1 "a") 1 0)

The disadvantage(?) is that you have to learn some Lisp, but that's a good thing: otherwise, how are you going to tinker with all those Emacs settings?

NickD
  • 27,023
  • 3
  • 23
  • 42
3

I don't know exactly what's going on here, but after doing a little debugging I found that this works:

| a |   |
| b |   |
#+TBLFM: $2=if("$1"=="(a)", 1, 0)

It looks to me like it's doing algebraic simplification in order to get an answer, and if that fails it can be left with a more complicated form than you expected. b = a ? 1 : 0 is a ternary expression that hasn't been evaluated to a value, presumably because a and b are treated as variables rather than strings. So you have to put them in quotes, but then "$-1" evaluates to a string with parenthesis for unknown reasons, so you have to include those parentheses on the other side of the equation as well.

db48x
  • 15,741
  • 1
  • 19
  • 23