Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure iterate a vector and look ahead/look behing

I do have to iterate over a vector, which in turn has maps as its items. I need to compare which map comes next, and sometimes I need to look what was in the map we looked at before. So it is necessary to have some kind of look ahead/look behind functionality. My current approach works, but I guess it is ugly, unidiomatic Clojure and I assume that there must be a better (more canonical) way to achieve this.

(let [result (apply str (map (fn [{position-before :position compound-before :compund } ; previous term (unfortunately we need to compare all three)
                                        {:keys [word position line tag stem compound grammarpos] :or {grammarpos "0" stem "" } } ; this maps to the current word
                                        {position-ahead :position compound-ahead :compound line-ahead :line}] ; this is for lookahead
                (do some stuff)) ;; now we have position, which is our current position, position-before and position-after to compare with each other
                ;; this is how we map:
                (into  '[{}] (conj grammar '[{}]))
                (next (into  '[{}] (conj grammar '[{}])))
                (next (next (into  '[{}] (conj grammar '[{}]))))))])

As for the request of the data-example, this is a part of the vector:

[{:tag "0", :position "0", :line "0", :stem "dev", :grammarpos "2625", :word "deva"} {:tag "0", :position "0", :line "0", :stem "deva", :grammarpos "4", :word "deva"}]

The job is to compare values for position, compound etc., sometimes look ahead, sometimes look behind.

like image 386
Sebastian_學生 Avatar asked Apr 25 '26 01:04

Sebastian_學生


1 Answers

You could iterate over a partition of your vector, with a size of 3 and step of 1. Then for each element in the vector, you also get the before and after that you can study as you iterate with a for or reduce.

Some examples: https://clojuredocs.org/clojure.core/partition

like image 111
johnbakers Avatar answered Apr 28 '26 05:04

johnbakers