If then statement vs Grid

My goal is to create a piecewise function in Julia parsimoniously.
u(x,y) = y if x = 0
u(x,y) = y -1 if x \neq 0
I get the following:

julia> FC(x) = (x==0):(0):(1)
FC (generic function with 1 method)

julia> u(x,y) = y - FC(x)
u (generic function with 1 method)

julia> u(1,0)
ERROR: ArgumentError: step cannot be zero
Stacktrace:
 [1] steprange_last(start::Int64, step::Int64, stop::Int64)
   @ Base .\range.jl:221
 [2] StepRange
   @ .\range.jl:208 [inlined]
 [3] StepRange
   @ .\range.jl:263 [inlined]
 [4] _colon
   @ .\range.jl:24 [inlined]
 [5] Colon
   @ .\range.jl:22 [inlined]
 [6] Colon
   @ .\range.jl:10 [inlined]
 [7] FC
   @ .\REPL[3]:1 [inlined]
 [8] u(x::Int64, y::Int64)
   @ Main .\REPL[4]:1
 [9] top-level scope
   @ REPL[5]:1

Problem is I want the function FC(x) = (x==0):(0):(1) to return 0 for x=0 and 1 for x\neq 0.
Instead of being an if/else statement, this function returns a StepRange.

And yes I know how to do this the long way…

I’m not sure why you’re using ranges for this. Why not:

u(x,y) = y - (x != 0)

or

u(x,y) = x == 0 ? y : y - 1

?

That’s just the function FC(x) = x != 0, or simply the function !iszero. (A boolean value true/false in Julia corresponds to 1/0, respectively.)

1 Like

I totally forgot the ? in the if/then.
Here is what I wanted:
u(x,y) = y - ( (x == 0) ? 0 : 1)

i.e. y - (x != 0).