Why a symbol starting with a number needs to be between brackets?

For example

function dayp(interval = :1day)   # errors
   if interval == :1day
        return 1
    elseif interval == :1week
        return 7
    end
end

One needs to do:

function dayp(interval = :(1day))
...

and then call the function using: dayp(:(1day))

it’s a parsing thing, I’m not sure why but :1 gets parsed as 1, so it tries to do 1 * day.

You want Symbol("1day"), as :(1day) is creating an expression, which is different.

2 Likes

pdeffebach thank you very much for the explanation. But then, I suppose, one has to call the function as dayp(Symbol("1day")) which is not very convenient. In this case it would possibly make more sense to use just Strings instead of Symbols, something I would like to avoid since I am using Symbols everywhere else.

Yeah. Or use day1 instead of 1day

If you are using Symbols because their literals are just a single character shorter than String characters, well, then this really throws a wrench at your choice. However, if you choose to use Symbol for any better reason, then the fact it become more verbose should not be so much of a problem.

1 Like

Or yet, use :one_day (if "1day" is not a viable option).

Sure. The inconvenience is that the users of my scripts are students who most likely will get confused if they will need to change to strings the usual symbols they got used to. Of course they can always use instead day1 or m30 (instead of 30m for 30 minutes), which seems to be the best solution even if a little awkward at first.

1 Like

Alternatively, you could remove the use of Symbols entirely by making use of the built-in Date tools:

julia> using Dates

julia> function dayp(interval::DatePeriod = Day(1))
         return Dates.value(Day(interval))
       end
dayp (generic function with 2 methods)

julia> dayp(Day(1))
1

julia> dayp(Week(1))
7

julia> dayp(Week(3))
21

This avoids the issue you’re dealing with and avoids needing to hard-code the number of days in every possible number of weeks by hand.

You can even do:

julia> const day = Day(1)
1 day

and now the implicit multiplication of 1day will actually just work:

julia> 1day
1 day

julia> 2day
2 days

julia> 3day
3 days

julia> dayp(3day)
3
4 Likes