Jump to content

Talk:Four bit adder: Difference between revisions

(→‎C++ code size: On golf, idiomatic code, and moved to a subpage.)
(→‎Clojure solution: new section)
Line 261:
(P.S. it would be instructive to know a little about how the code was written. Was it written for this RC task alone? Was a lot of the code generated by an IDE? ...) --[[User:Paddy3118|Paddy3118]] 04:59, 1 October 2011 (UTC)
: Concur on subpage, and done. I think it was very probably written for Rosetta Code; the usage of a namespace named 'rosetta' is good indicator. --[[User:Short Circuit|Michael Mol]] 11:42, 1 October 2011 (UTC)
 
== Clojure solution ==
 
I added a second Clojure solution to show what I think is more idiomatic Clojure code. Because Clojure does not have TCO (which unavailable in Java), it's generally not a good idea to write recursive code in the old Lisp style as done in the original solution ('''n-bit-adder''' function). If possible, you should use the special form '''recur''' in a tail-call position to avoid growing the stack. But most of the time, it's better to find a solution using '''reduce''' if you can.
 
The second solution shows a couple of interesting language features. First, it uses destructuring to simplify extracting multiple values out of a vector (see my '''full-adder''' function). Second, it uses '''reduce''' in '''nbit-adder''' which is a good thing for Clojure programmers to learn. Also, the pre-condition (''':pre''') is a nice way to check for errors. It can be turned off without having to change the source.
 
The choice of big endian or little endian is arbitrary, but I think big endian is easier to read. That requires a little extra fiddling with how the bits are fed to the reduce function, but also shows off the '''rseq''' function, which is constant-time reverse for vectors.
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.