简体   繁体   中英

a function written in Julia programming language doesn't stop on return

I'm currently doing the assignment of a subject I'm coursing in university (Programming Languages Theory). Part of this assignment consists in solving problems that, while are relatively simple to be solved using an imperative/structured approach; are not so trivial when one's using a functional language (like, for example, matrix multiplication).

So, we have 10 problems to solve, and we're allowed to use any functional language (or, at least, a programming language that supports functional programming). So, while I'm really familiar with Haskell and Miranda, I was learning by myself how to program in Julia, therefore I chose it as the programming language for this job.

One of the problems I have to solve is to create a program that, given a string "S" as input, it returns "true" if the string contains any substring that's palindrome and whose length is greater (or equal) than 3.

So, I used a "brute-force recursive" approach: test if the input string S is palindrome, if it is, return true, otherwise recursively check if S without its first character or without its last character is palindrome. If there's no palindrome substring greater or equal than 3, return false

This will create a recursion tree that checks all possible substrings in S. Even though this algorithm is exponential , it does the job. Also, I can't use dynamic programming, divide-and-conquer, memoization, efficient data structures or any " dank algorithm design technix " - so, I have to stick with the pure functional, recursive approach.

Here's the code:

function SubPalin(S)
  if length(S) > 2
    if palindromeChecker(S) == true
      return true
    else
      SubPalin(S[2:end])
      SubPalin(S[1:end-1])
    end
  else
    return false
  end
end

Note: palindromeChecker is a function that checks if a substring is palindrome (yeah, obvious, I know)

The problem is: while this code do check all possible substrings greater than 3, it doesn't halt when it finds a palindrome substring. What's even weird is that, after some tests, I found out that the code doesn't stop even when it returns true. It just keeps going till it finds the recursion base case.

So, what's happening? I'm just dumb and I can't see the bug or there's something wrong with the language?

You may want to consider something like this line of code in your first else branch? return SubPalin(S[2:end]) || SubPalin(S[1:end-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM