Arc Forumnew | comments | leaders | submitlogin
how to refactor this code?
3 points by adm 5587 days ago | 6 comments
I am trying to write a routine which will be something like unix filter: open file process each line close file

here is the code(this may not compile yet :)).

my question is how to refactor 'ffilter, 'ffilter1 & 'ffilter2 methods??

Thanks.

  (def filltbl (keys vals (o tbl (table)))
    ((map (fn (k v) (= tbl.k v)) keys vals)
      tbl))

  ; 'func takes a hashtbl
  (def ffilter2 (file func fldnames (o fldsep whitec))
    (let nln 0
      (w/infile in file
       (whilet line (readline in)
        (++ nln)
        (func (filltbl (fldnames) (tokens line fldsep)))
        ))
        nln))

  ; 'func takes a list
  (def ffilter1 (file func (o fldsep whitec))
   (let nln 0
    (w/infile in file
      (whilet line (readline in)
        (++ nln)
        (func (tokens line fldsep))))
        nln))

  ; 'func directly works on line
  (def ffilter (file func )
   (let nln 0
    (w/infile in file
      (whilet line (readline in)
        (++ nln)
        (func line)))
        nln))
;; some usage

  (def cat (f)
    (filter f [pr _]))
  (def grep (f pat)
    (filter f [if (matchpat pat _) pr _]))
  (def cut (f fldsep pos)
    (filter1 f [pr (pos _)] fldsep))
  (def loadcsv (f)
    (filter2 f [pr _] #\,))


2 points by CatDancer 5587 days ago | link

What is your goal for the refactoring?

-----

1 point by adm 5587 days ago | link

those three methods are similar except line processing. Can't we refactor those, where they will call a single method or macro?

-----

3 points by CatDancer 5587 days ago | link

untested, but perhaps something like this?

  (def ffilter1 (file func (o fldsep whitec))
    (ffilter file (fn (line)
                    (func (tokens line fldsep)))))
and similarly define ffilter2 using ffilter as well.

-----

1 point by adm 5587 days ago | link

  (def ffilter1 (file func (o fldsep whitec))
    (ffilter file [tokens _ fldsep]))
this should work? (just curious: since I don't have access to arc right now).

-----

3 points by absz 5587 days ago | link

You want

  (def ffilter1 (file func (o fldsep whitec))
    (ffilter file [func:tokens _ fldsep]))

-----

1 point by adm 5587 days ago | link

oops! I will test with this.

-----