Author Topic: Anybody have some easy sorting routines?  (Read 1478 times)

0 Members and 1 Guest are viewing this topic.

ifncdylan

  • Guest
Anybody have some easy sorting routines?
« on: March 13, 2017, 07:45:31 PM »
Hey all, I've had a bit of a look around but I can't find a good set of routines for sorting collections - in this case, I have a collection of blocks and I want to sort them numerically by an attribute.

Essentially I just want to run a function like (sortby '(lambda (a b) ((LM:vl-getattributevalue a "NAME") > (LM:vl-getattributevalue b "NAME")) ListOfBlocks) but I can't seem to get one working like that. I've been away from LISP for a while...feeling rusty! Can anyone help oil my gears?

ronjonp

  • Needs a day job
  • Posts: 7527
Re: Anybody have some easy sorting routines?
« Reply #1 on: March 13, 2017, 08:15:46 PM »
Use vl-sort 😀

Windows 11 x64 - AutoCAD /C3D 2023

Custom Build PC

ifncdylan

  • Guest
Re: Anybody have some easy sorting routines?
« Reply #2 on: March 13, 2017, 08:36:17 PM »
rather counterintuitively, vl-sort doesn't work on visual lisp collections :(

ronjonp

  • Needs a day job
  • Posts: 7527
Re: Anybody have some easy sorting routines?
« Reply #3 on: March 14, 2017, 09:01:40 AM »
If you're using lisp why are you not sorting lists? It's quite easy  ;) .
Code - Auto/Visual Lisp: [Select]
  1.   'cdr
  2.     (mapcar (function (lambda (x) (cons (atof (lm:vl-getattributevalue x "NAME"))) x)) listofblocks)
  3.     (function (lambda (a b) (< (car a) (car b))))
  4.   )
  5. )

Windows 11 x64 - AutoCAD /C3D 2023

Custom Build PC

Lee Mac

  • Seagull
  • Posts: 12913
  • London, England
Re: Anybody have some easy sorting routines?
« Reply #4 on: March 14, 2017, 01:25:06 PM »
Alternatively, using vl-sort-i:
Code - Auto/Visual Lisp: [Select]
  1.    '(lambda ( n ) (nth n listofblocks))
  2.     (vl-sort-i (mapcar '(lambda ( b ) (atof (lm:vl-getattributevalue b "NAME"))) listofblocks) '<)
  3. )

ifncdylan

  • Guest
Re: Anybody have some easy sorting routines?
« Reply #5 on: March 15, 2017, 08:24:54 PM »
Oh god.. thanks guys! I just realized again how amazing the mapcar/lambda combo is. I was starting to make really extensive use of it for processing the visual lisp objects before, but I completely forgot about it. I just need to really wrap my head around vlax-map-collection and vlax-put/get-property in conjunction with mapcar/lambda and the world will be all right again :)

The boss sprung a bunch of code jobs on me out of nowhere and I was struggling to get back into the groove. These examples have certainly inspired me again! Reminds me, I have some code I wrote for regex matching, I might post it in another thread and see if you legends can improve on it.