This whole HN attitude of pristine code is killing me. This is a piece of code in a GIST and solves the problem in three lines, it is clearly not intended for production use in a large code base.
Please stop searching for something wrong and enjoy what is presented in all of its glory.
It should be called "0,5kb scala contest" than "solving x with scala", to avoid misunderstanding.
Another way this code could be useful would be to showcase good readability practices, but it doesn't.
OTOH, the gist has a low cognitive load provided one understands funtional notation. I can look at his four lines of code and see that this is a correct solution, because each atom of the function can be reasoned about separately and then composed into the whole. The same is much more difficult with the looping solutions that have been presented as peers to this comment. These solutions have a higher cognitive load because proving correctness requires a full trace of the algorithm, while keeping all of the variables in working memory as you go.
tl;dr; The OP presented a clear and clever solution. I'll allow it. ;)
I think there's a difference between the cognitive load of the solution and the cognitive load of the implementation. The cognitive load of the general solution for queens is somewhat high, but that's why it's a well-known puzzle. But this implementation is practically a description of the problem itself. It's literally selecting (filter) from all queen arrangements (permutations) where the queens aren't conflicting (described via map and zipWithIndex).
Said in other words: 15 line solutions cannot break into the higher-order pattern-recognition space, since these solutions rely on context specific naming.
Naming is one of the most difficult parts of software engineering, so we should try to rely on contextual patterns in order to minimize naming altogether.
The same issue arises when factoring Forth code into tiny "words" (one of the advantages of a concatenative language): you have to name sequences of operations that don't have an obvious problem-space concept behind them.
#!/usr/local/bin/perl
#borrowed from Nick Holloway <[email protected]>, 27th May 1993.
my $size=8;my @cols=(0..$size-1);
sub nextq {
(print( "@_\n" ),return) if @_ == $size;
foreach my $col(@cols) {
next if grep($_ == $col, @_);
my $row=@_;next if grep ($_ == $col-$row--, @_);
my $row=@_;next if grep ($_ == $col+$row--, @_);
nextq(@_,$col);
}
}
nextq();
Not sure if it's slower or more resource intensive than the Scala solution. I'm sure it could be golfed down to be smaller than the Scala counterpart. It has fewer characters already, even with the comments intact. -l /.{@ARGV}/?print:map/((.).*)(.)(??{$2!=$3&&length$1!=abs$2-$3&&0})/||do$0,$_.1.."$_@ARGV"This is no more indicative of Perl than the Obfuscated C contest is indicative of C.
!function r(y,a,z,b,x){for(x=y--?-1:print(a);++x<n;z&c|b&d||r(y,a+1?a+' '+x:x,z|c,b|d))c=(1|1<<y+9)<<x,d=1<<9+x-y}(n=readline())
http://golf.shinh.org/reveal.rb?N+Queens/murky-satyr_1217229... my $size=8;my @cols=(0..$size-1);
my $row=@_;next if grep ($_ == $col-$row--, @_);
my $row=@_;next if grep ($_ == $col+$row--, @_);
Strictly speaking that's 6 lines of code concatenated into 3.But as you said, it would be relatively easy to golf that down and still keep the program logic.
sub nextq {
my $sz=8;
(print("@_\n"),return) if @_ == $sz;
foreach my $col(0..$sz-1) {
my $row;
if (grep($_==$col,@_)) {next} else {$row=@_}
if (grep($_==$col-$row--,@_)) {next} else {$row=@_}
if (grep($_==$col+$row--,@_)) {next} else {$row=@_}
nextq(@_,$col);
}
}
nextq();I was thinking more along the lines of using the one line conditional:
condition ? first_expression : second_expression;
eg sub nextq {
(print( "@_\n" ),return) if @_ == (my $size = 8);
foreach my $col(0..$size-1) {
my ($row, $next);
grep ($_ == $col, @_) ? $next=1 : $row=@_;
grep ($_ == $col-$row--, @_) ? $next=1 : $row=@_;
grep ($_ == $col+$row--, @_) ? $next=1 : $row=@_;
nextq(@_,$col) unless $next;
}
}
nextq();
The `$next` ugliness is due to not being allowed to use the `next` inside a one line conditional. There's probably cleaner ways of doing the above though. But that was only a quick hack.This sort of line counting is just for fun.
sub nextq {
my $sz=8;
(print("@_\n"),return) if @_ == $sz;
o: foreach my $col(0..$sz-1) {
my($u,$d)=(scalar(@_),scalar(@_));
for (@_) {next o if($_==$col or $_==$col-$u-- or $_==$col+$d--)}
nextq(@_,$col);
}
}
nextq();Nice code though.
That "print and return with postfix" is the gold star. /s
Edit: Perl's also not the only language that supports the comma operator, predicate if, ternary, and other things that seem to bother you.
You can of course then go on and get increasingly clever, but I think you should at least aim for backtracking.
For someone completely unfamiliar with FP, the cognitive load might be high. However, even basic familiarity with FP constructs is enough to understand and appreciate the code.
I would always prefer a map/fold to a for-loop. Removing the "i" and its book keeping reduces cognitive load. However, a Python list comprehension often becomes too big an expression if you use too much filtering. Extracting the filter into its own function an giving it a good name compartmentalizes the complexity, though. All in all, it is quite subjective.
If you are used to premutations, mapping, zipping, filters the code becomes quite readable. I'm pretty sure there is C code which confuses a Haskell programmer but would be considered "clear and readable" by the average C programmer.
from itertools import permutations
def n_queens(n):
for p in permutations(range(n)):
if len({c + i for i, c in enumerate(p)}) == len({c - i for i, c in enumerate(p)}) == n:
yield p def n_queens(n):
yield from (p for p in permutations(range(n))
if len({c + i for i, c in enumerate(p)}) ==
len({c - i for i, c in enumerate(p)}) == n)
It also illustrates how much neater list comprehensions can be in Python versus map/filter since its lambda functions are fairly verbose (even though there's a straightforward correspondence between them): def n_queens(n):
return filter(lambda p:
len(set(map(lambda x: x[1] + x[0], enumerate(p)))) ==
len(set(map(lambda x: x[1] - x[0], enumerate(p)))) == n,
permutations(range(n)))Python's iterators are mutation-based, so not really functional. `yield` is based around pause-resume of function execution, so not really functional. `permutations` is just a function that wraps a list (or iterator coercible to one (which mutates the iterator)) and returns a (mutable) iterator.
A `for` comprehension desugars to a `for` loop with `yield` if it's a lazy comprehension, `append` if it's a list comprehension or `add` if it's a set comprehension, which of course involves mutation.
Basically nothing here is mutation free. That, at least IMO, means it's not functional.
It's great that functional languages were first to catch onto these ideas, but that doesn't mean that anything else that uses them becomes functional. The interface isn't even functional, since in code like
foo = iter((1, 2, 3))
{x for x in foo}
`foo` is mutated. No "true" functional language would accept that ;).Sure, but Python wasn't the first imperative programming language. (An aside: that's not strictly true anyway; the error thrown when you do 1 + [] is a side effect.)
There is next to no cognitive load in this 4-line solution. Brute-force attack on every permutation. I would say that anyone find there to be an excessive cognitive load would be someone that is not familiar with scala nor functional programming.
I find this type of code an anti pattern of how good code should be. This solution has a high "cognitive load" imho: http://chrismm.com/blog/how-to-reduce-the-cognitive-load-of-...
I'd much rather see a 15-20 line solution that's clear and readable, than a 4 line solution that I have to reverse engineer.