Arc Forumnew | comments | leaders | submitlogin
2 points by partdavid 6104 days ago | link | parent

I'm not thrilled with this escript (Erlang), namely because Erlang provides a perfectly nice way to format the resulting lists but lojic dictates the output must be exactly the same, thus the fairly ugly business in main():

  #!/usr/bin/env escript
  
  -import(lists, [seq/2, reverse/1]).
  
  main([]) ->
     lists:foreach(fun(L) ->
                         io:format("[ ~s ]~n",
                                   [string:join(
                                      [ integer_to_list(I)
                                        || I <- L ], ", ")])
                   end, queens([], 0)).
                         
  
  threatens(Q, _, [Q|_], _) -> true;
  threatens(_, _, [], 0) -> false;
  threatens(Q, I, [Q2|Queens], I2) ->
     if
        abs(I - I2) =:= abs(Q2 - Q) -> true;
        true -> threatens(Q, I, Queens, I2 - 1)
     end.
  
  is_valid([Q|Queens]) ->
     TL = length(Queens),
     not threatens(Q, TL + 1, Queens, TL).
  
  queens([], _) -> queens([ [X] || X <- seq(1, 8) ], 8);
  queens(Tree, 1) -> Tree;
  queens(Tree, Place) ->
     queens([ [N|Node] || N <- seq(1, 8),
                          Node <- Tree,
                          is_valid([N|Node]) ],
            Place - 1).
Note that threatens/4 there does short-circuit and avoids evaluating needless cases, without "return."


2 points by lojic 6104 days ago | link

"but lojic dictates"

I prefer the word encourage :) I know it's nitpicky, but the idea was to not simply use a native print. Of course, had I required the 'pp' Ruby lib, I could have just said:

  pp stack   # => [ 1, 2, 3, ... , 8 ]

-----

2 points by partdavid 6104 days ago | link

I liked the pun in "lojic dictates", though :)

My point was more that having to put spaces in meant doing it myself rather than just io:format("~p~n", [Answer]).

-----

1 point by lojic 6103 days ago | link

Ah, I missed the pun - nice.

Your point is my point. I wanted to see how well Arc handles formatting something that didn't fit neatly into an expected pattern.

Ruby has several formatting techniques that are quite nice:

1) String interpolation. You can insert an expression into a spring by using #{expression}

2) String formatting. You can use sprintf style patterns in strings via format or the % operator. For example:

  puts "%4.1f hours" % hours
  puts "%4.1f hours and %4.1f minutes" % [hours, minutes]
So, does Arc have format now?

-----