0

The function below splits the text variable into a sequence of characters that is steps long. The only problem is I can't figure out how to return the resulting list, which I need to compute its Shannon entropy for several values of step.

(defn split-text [text step]

  (loop [i 0 result []]
    (when (<= (+ i step) (count text))
      (recur (+ i step)
             (conj result (subs text i (+ i step)))))))
1
  • 1
    as the answer below says, you should return result in a false condition branch. You can also do something like this, to reduce code complexity: (defn split-text [text step] (map (partial apply str) (partition step text))) Commented May 6, 2020 at 8:53

1 Answer 1

1

You need to return the result from the loop:

(defn split-text [text step]
  (loop [i 0 result []]
    (if (> (+ i step) (count text))
      result  ;; <== here
      (recur (+ i step)
             (conj result (subs text i (+ i step)))))))

Also, the last chunk will be lost if it's less than step characters long. If you want to keep it:

(defn split-text [text step]
  (loop [tail text result []]
    (if (empty? tail)
      result
      (let [len (min step (count tail))]
        (recur (subs tail len)
               (conj result (subs tail 0 len)))))))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is exactly what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.