Processing a file character by character in Clojure

后端 未结 3 2001
礼貌的吻别
礼貌的吻别 2020-12-20 21:38

I\'m working on writing a function in Clojure that will process a file character by character. I know that Java\'s BufferedReader class has the read() method that reads one

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-20 22:10

    You're pretty close - keep in mind that Strings are a sequence. (concat "abc" "def") results in the sequence (\a \b \c \d \e \f).

    mapcat is another really useful function for this - it will lazily concatenate the results of applying the mapping fn to the sequence. This means that mapcating the result of converting all of the line strings to a seq will be the lazy sequence of characters you're after.

    I did this as (mapcat seq (line-seq reader)).

    For other advice:

    • For creating the reader, I would recommend using the clojure.java.io/reader function instead of directly creating the classes.
    • Consider breaking apart the reading the file and the processing (in this case printing) of the strings from each other. While it is important to keep the full file parsing inside the withopen clause, being able to test the actual processing code outside of the file reading code is quite useful.
    • When navigating multiple (potentially nested) sequences consider using for. for does a nice job handling nested for loop type cases.

      (take 100 (for [line (repeat "abc") char (seq line)] (prn char)))

    • Use prn for debugging output. It gives you real output, as compared to user output (which hides certain details which users don't normally care about).

提交回复
热议问题