I was wondering if there was a way to take a list of numbers (digits), and truncate the numbers together to be one large number (not addition) in Scheme. For example, I would want
(foo '(1 2 3 4))
;=> 1234
Does Scheme have a built in function to do this?
There are a number of languages that are in the Scheme family, and there are a few versions of Scheme, too. If you're using one, e.g., Racket, that includes a left associative fold (often called
foldl
,fold
, orreduce
, though there are other variations, too), this is pretty straightfoward to implement in terms of the fold. Folds have been described in more detail in these questions and answers:fold
can be viewed as an iterative construct (and in Scheme, which mandates tail call optimization, is compiled to iterative code), and also includes an implementation offoldl
for Schemes that don't have it.reduce
provides a somewhat more convenient interface than what's provided in some of the Scheme libraries.Here's what the code looks like in terms of
foldl
:If your language doesn't have it,
foldl
is pretty easy to write (e.g., my answer to the one of the questions above includes an implementation) and use the preceding code, or you can write the whole function (using the same approach) yourself:You can make that a bit more concise by using a named
let
: