# When the ternary operator fails

**URL:** <https://discourse.julialang.org/t/when-the-ternary-operator-fails/91332>\
**Category:** General Usage\
**Created:** [December 7, 2022, 1:55am UTC](https://discourse.julialang.org/t/when-the-ternary-operator-fails/91332 "2022-12-07T01:55:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jake](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jake/32/46007_2.png) [@Jake](https://discourse.julialang.org/u/Jake)\
**Post date:** [December 7, 2022, 1:55am UTC](https://discourse.julialang.org/t/when-the-ternary-operator-fails/91332/1 "2022-12-07T01:55:38Z")

</div>

In the specific case where I want the ternary operator to give me an operator, it fails, but the if then else approach works. I expect there is an explanation, or maybe it is a bug.

What does not work

```julia
julia> a = "1+2";

julia> op = contains(a, '+') ? + : -
ERROR: syntax: whitespace not allowed after ":" used for quoting
Stacktrace:
 [1] top-level scope
   @ none:1

```

and what does work

```julia
julia> a = "1+2";

julia> if contains(a, '+')
           op = +
       else
           op = -
       end
+ (generic function with 206 methods)

julia> op(4,5)
9

```

---

<div class="post-metadata">

**Author:** ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)\
**Post date:** [December 7, 2022, 2:18am UTC](https://discourse.julialang.org/t/when-the-ternary-operator-fails/91332/2 "2022-12-07T02:18:32Z")

</div>

you are running into a disallowed parser state (ending an expression with `-`  
this is an opportunity to use `ifelse`

```julia
a = "1+2"
op = ifelse(contains(a, '+'), +, -)
op == +

```

or, just enclose the operators in parens

```julia
a = "1+2"
op = contains(a, '+') ? (+) : (-)
op === +

```

---

<div class="post-metadata">

**Author:** ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)\
**Post date:** [December 7, 2022, 2:25am UTC](https://discourse.julialang.org/t/when-the-ternary-operator-fails/91332/3 "2022-12-07T02:25:13Z")

</div>

Parentheses can also resolve this issue:

```julia-repl
julia> op = contains(a, '+') ? (+) : -
+ (generic function with 208 methods)  

```

I would normally parenthesize both, but apparently the first was enough.
