Writing a function that requires 1 argument, when using it julia thinks I put 2 in

I have this in greet.jl

module greetings
export greet
function greet(greeting::String)
    if greeting == "hello" | greeting == "Hello"
        returnmsg = "Good morning"
    elseif greeting == "goodbye"
        returnmsg = "Good night."
    else 
        returnmsg = "What's up"
    end
    return returnmsg
end
end

I go into the repl and get an error, which looks like julia thinks I am giving it two arguments.

julia> include("greet.jl")
Main.greetings

julia> greetings.greet("hello")
ERROR: MethodError: no method matching |(::String, ::String)
Closest candidates are:
  |(::Any, ::Any, ::Any, ::Any...) at operators.jl:538
Stacktrace:
 [1] greet(::String) at /home/westly/greet.jl:4
 [2] top-level scope at REPL[2]:1
 [3] run_repl(::REPL.AbstractREPL, ::Any) at /build/julia/src/julia-1.5.3/usr/share/julia/stdlib/v1.5/REPL/src/REPL.jl:288

What am I doing wrong here?

The “or” operator you are probably expecting is || (not a single |).

That is another type of “or” operator, which one rarely uses.

2 Likes

Thanks, that worked.

Take a look at Mathematical Operations and Elementary Functions · The Julia Language

The | operator has higher precedence than ==, so you’re doing "hello" | greeting - this is fixed by adding parentheses to the expression:
(greeting == "hello") | (greeting == "Hello")

2 Likes

Thanks for the explanation.

This is parsed as greeting == ("hello" | greeting) == "Hello", since | has higher precedence than ==. You would have to write (greeting == "hello") | (greeting == "Hello") to use |.

As @lmiq commented, what you want is greeting == "hello" || greeting == "Hello": || is “logical or”, which is usually what is employed in boolean expressions (and has lower precedence than ==). | is a “bitwise or” operation, and is usually for bit arithmetic.

(They also differ in that || is short-circuiting, which is typically what you want in logical operations, and | is not.)

1 Like