Arc Forumnew | comments | leaders | submitlogin
2 points by sacado 6136 days ago | link | parent

  (def valid (stack)
    (with (q2 (- len.stack 1)
           result t)
      (each q1 (range 0 (- len.stack 2))
        (= result (and result
                       (isnt stack.q1 stack.q2)
                       (isnt (abs:- q1 q2) (abs:- stack.q1 stack.q2))))))

  (def queens (stack n)
    (if (is n 8)
      (prn stack)
      (each rank (range 1 8)
        (push rank stack)
        (if (valid stack)
          (queens stack (+ n 1)))
        (pop stack))))

  (queens '() 0)
It's a naïve implementation of what you wrote in Ruby. It should work, however I didn't try it. It is not really optimal, as there is no return in my code. Anyway, it's quick and dirty...


2 points by almkglor 6136 days ago | link

If you're on arc-wiki, you can use the breakable: modifier to create a breakable with/let:

  (def valid (stack)
    (breakable:let q2 (- len.stack 1)
      (each q1 (range 0 (- len.stack 2))
        (if (or (is stack.q1 stack.q2) (is (abs:- q1 q2) (abs:- stack.q1 stack.q2)))
          (break nil)))
      (break t)))
edit: BTW, your 'valid function didn't actually return the result ^^

-----

1 point by sacado 6135 days ago | link

oh, right, each returns nil...

Thks for the "breakable" info

-----

2 points by lojic 6135 days ago | link

Is there a way to return in Arc?

-----

2 points by sacado 6135 days ago | link

Sure, ccc is here for that. Let's say we want the equivalent of this Python code :

  def a:
    for i in (1, 2, 3):
      if i < 2:
        return i

    return None
It can be written this way in Arc :

  (def a (return)
    (each i '(1 2 3)
      (if (< i 2)
        (return i)))
    nil)

  arc> (ccc a)
  1
To those who don't know ccc : in this code, return is not a defined macro or function, it is the current continuation, waiting for a value. We could have called it another way, k for example.

Once you "throw" it a value (i in this case), it's happy and goes on to the next calculation. (ccc a) thus tells to perform a and, once the return parameter is called, exit a and go back to the REPL (with the specified value).

-----

2 points by lojic 6135 days ago | link

Thanks for the quick reply. That seems like an awkward way to accomplish a simple thing - Python & Ruby win on this IMO.

I submitted a new article ( http://arclanguage.com/item?id=4431 ) on the topic. It might be good to re-post your comment there and have followups on that thread.

-----

2 points by almkglor 6135 days ago | link

better is point:

  (def a ()
    (point return
      (each i '(1 2 3)
        (if (< i 2)
          (return i)))
      nil)))
That said, the breakable: macro simply compiles down to (point break ...)

-----