There are several languages ββthat do not support loops (i.e. for and while), and as a result, when you need to repeat the behavior, you need to use recursion (I believe J has no loops). In many examples, recursion requires much less code. For example, I wrote the isPrime method, it took only two lines of code.
public static boolean isPrime(int n) { return n!=1&&isPrime(n,2); }
public static boolean isPrime(int n,int c) { return c==n||n%c!=0&&isPrime(n,c+1); }
An iterative solution will require much more code:
public static boolean isPrime(int n) { if(n==1) return false; int c=2; while(c!=n) { if(n%c==0) return false; } return true; }
Another good example is working with ListNodes, for example, if you want to check if all the elements in the ListNode are the same, the recursive solution will be much simpler.
public static <E> boolean allSame(ListNode<E> list) { return list.getNext()==null||list.getValue().equals(list.getNext().getValue())&&allSame(list.getNext()); }
The iterative solution would look something like this:
public static <E> boolean allSame(ListNode<E> list) { while(list.getNext()!=null) { if(!list.getValue().equals(list)) return false; list=list.getNext(); } return true; }
As you can see, in most cases recursive solutions are shorter than iterative solutions.
source share