Any package or provision to suggest alternative/fast code

Suppose I have written a piece of code to check whether a string say “malayalam” is a palindrome.

s = "malayalam"
s == reverse(a)

.
An alternative is s == s[end:-1:1].

Is there a package or provision to suggest alternates, efficient code in Julia.
My question is in general sense for any piece of code.

I don’t know if this is possible in general. In a general case, it’s unclear if s[end:-1:1] and reverse(s) are equivalent, let alone to judge which one is more efficient. There are certain patterns that the VS Code linter suggests.

3 Likes

s[end:-1:1] is not functionally equivalent to reverse(s) in general, because s[end:-1:1] is incorrect for non-ASCII strings:

julia> s = "αβγ"
"αβγ"

julia> reverse(s)
"γβα"

julia> s[end:-1:1]
ERROR: StringIndexError: invalid index [4], valid nearby indices [3]=>'β', [5]=>'γ'

The problem is that for non-ASCII strings, the string indices are not consecutive integers:

julia> collect(eachindex(s))
3-element Vector{Int64}:
 1
 3
 5

More generally, if you are checking for palindromes that might include non-ASCII strings, even reverse(s) might not do quite what you want. The reverse(s) function reverses the codepoints of a string — mainly useful for reverse-order string processing such as regex searches (see the discussion in julia#6165) — but as explained in the manual this may not correspond to your intuitive notion of string reversal for strings containing combining characters. In that case, you might want to reverse graphemes instead:

julia> using Unicode

julia> ispalindrome(s::AbstractString) = s == join(reverse(collect(graphemes(s))))

julia> ispalindrome("ax̂a")
true

julia> reverse("ax̂a") == "ax̂a"
false

julia> reverse("ax̂a")
"âxa"

Unicode makes string processing more complicated than most people realize.

7 Likes

In general, is there a package or tool which suggests alternate for any piece of code.

Well, people use LLM machine-learning tools for this sort of thing sometimes, ala ChatGPT. Caveat emptor, though — those tools work best when you ask about coding problems for which there are zillions of similar examples online that it can interpolate from, but they will also cheerfully and confidently give you wrong answers.

For example, “write julia code to check if a string is a palindrome” in ChatGPT gives:

function is_palindrome(str)
    # Remove spaces and convert the string to lowercase for a case-insensitive check
    str = replace(lowercase(str), r"\s+" => "")
    
    # Compare the original string with its reverse
    return str == reverse(str)
end

which is pretty reasonable, but it doesn’t handle multi-character graphemes properly. If you tell it “fix it to reverse graphemes”, it changes the last line to str == reverse(graphemes(str)), which is incorrect code because graphemes returns an iterator that is not reversible unless you collect it first.

3 Likes