Scheme Binary List to Decimal Sum - list

A function that takes a list of binary numbers and returns their decimal sum.
Call: (addBinary '(1101 111 10 101))
(define (addBinary binaryList))
returns 27

Tested in Racket and Guile:
(define (addBinary binaryList)
(foldl ; or fold, depending on dialect
(lambda (n r)
(+ r (string->number (number->string n) 2)))
0 binaryList))

Related

infinite sequence scheme to make infinite sequence

I have a project in scheme in which I need to implement an infinite sequence of numbers. I can't use any scheme-built-in complex functions, and I just do not know how to make my sequence infinite without program crashing in infinite loop. I don't have to really output it, but I need to be able to use it.
(seq n) ;;output: n,n+1,n+2,n+3.... to infinity (seq 5) ->5,6,7,8,9...
Right now I did a sequence until n+7, but I need this to infinity:
(define (seq n)
(define (asc-order LIST counter)
(cond ((= counter (+ n 7)) LIST)
(else (asc-order (append LIST (cons (+ counter 1) '()))
(+ counter 1)))))
(asc-order '() (- n 1))
)
IO example (It works, but I need it infinite sequence):
>(define s (seq 3))
>(car s)
3
You can represent an infinite sequence as a function that produces one element at a time. The user (consumer) can then call the function each a new element of the sequence is needed.
An example:
(define (f x) (* x x))
(define seq
(let ()
(define n 0) ; current index
(lambda () ; the function that is to be called repeatedly
(define a (f n)) ; compute the new element
(set! n (+ n 1)) ; compute new index
a))) ; return the new element
(seq) ; compute element 0
(seq) ; compute element 1
(seq) ; ...
(seq)
(seq)
(seq)
This evaluates to:
0
1
4
9
16
25
In order to write (sequence->list s n) which computes the first n elements of the sequence s, make a loop that calls s in total n times - and collect the results in a list.
The key is to delay evaluation of the list by wrapping a procedure around it.
Here's the simplest implementation I can think of.
It's only "lazy" in the tail.
(define (seq n)
(cons n (lambda () (seq (+ n 1)))))
(define (seq-car s)
(car s))
(define (seq-cdr s)
((cdr s)))
Example use:
; Get the 'n' first elements of 's'.
(define (seq-take n s)
(if (<= n 0)
'()
(cons (seq-car s) (seq-take (- n 1) (seq-cdr s)))))
> (define s (seq 10))
> s
'(10 . #<procedure>)
> (seq-take 5 s)
'(10 11 12 13 14)
Here is another solution using delayed evaluation:
(use-modules (ice-9 receive))
(define (seq f)
(let loop ((n 0))
(lambda ()
(values (f n) (loop (1+ n))))))
(define squares (seq (lambda (x) (* x x))))
(receive (square next) (squares)
(pk square) ;; => 0
(receive (square next) (next)
(pk square) ;; => 1
(receive (square next) (next)
(pk square) ;; => 4
(receive (square next) (next)
(pk square))))) ;; => 9

Concatenating list elements - Scheme

If i have a scheme code that generates the following result: (i'm using cons)
'((1 . 0) . 0)
How can i take this, and just simply display 100 as if it were just one integer number and not a list presented with those dots and parenthesis?
Thanks!
EDIT:
my full code:
(define (func X)
(if ( <= X 3 )
X
(cons (modulo X 4) (func(floor(/ X 4)) ))
))
If I understand correctly, you're trying to convert a number from base 10 to base 4, and then display it as a number, but there are several problems with your implementation.
You're building a list as output - but that's not what you want, you want a number. Also, you're traversing the input in the wrong order, and that's not the correct way to find the quotient between two numbers. Perhaps this will help:
(define (func X)
(let loop ((n X) (acc 0) (mult 1))
(if (< n 4)
(+ (* mult n) acc)
(loop (quotient n 4)
(+ (* mult (modulo n 4)) acc)
(* mult 10)))))
Alternatively, you could output a string to stress the fact that the output is not in base 10:
(define (func X)
(let loop ((n X) (acc ""))
(if (< n 4)
(string-append (number->string n) acc)
(loop (quotient n 4)
(string-append (number->string (modulo n 4)) acc)))))
It'll work as expected:
(func 16)
=> 100
Oscar Lopez's answer is excellent. I can't help adding that this problem doesn't need the "loop" construct:
;; translate a string to a base-4 string.
(define (func n)
(cond [(< n 4) (number->string n)]
[else (string-append (func (quotient n 4))
(number->string (modulo n 4)))]))

Create a n x n board in Racket using build-list

So I'm trying to a build a function in which it creates a list of positions on a board based on an inputed dimension.
(define (create-board dimension) ...)
Where dimension would be a number from 1 to 9, inclusive.
So the output would a list of lists of board locations where the board locations would be a 2 digit number, the first digit being the row number, second being the column number.
Example:
(create board 3) -> (list (list 11 12 13) (list 21 22 23) (list 31 32 33)))
Additionally, this is supposed to be done without recursion or helper functions, only abstract list functions.
In Racket, there's a very idiomatic solution using iterations and comprehensions:
(define (create-board dim)
(for/list ([i (in-range 1 (add1 dim))])
(for/list ([j (in-range 1 (add1 dim))])
(+ (* 10 i) j))))
Alternatively, using only elementary list procedures:
(define (create-board dim)
(map (lambda (i)
(map (lambda (j)
(+ (* 10 i) j))
(build-list dim add1)))
(build-list dim add1)))
For example:
(create-board 3)
=> '((11 12 13) (21 22 23) (31 32 33))

Scheme number to list

I need a subroutine for my program written in scheme that takes an integer, say 34109, and puts it into a list with elements 3, 4, 1, 0, 9. The integer can be any length. Does anyone have a trick for this? I've thought about using modulo for every place, but I don't think it should be that complicated.
The simplest way I can think of, is by using arithmetic operations and a named let for implementing a tail-recursion:
(define (number->list num)
(let loop ((num num)
(acc '()))
(if (< num 10)
(cons num acc)
(loop (quotient num 10)
(cons (remainder num 10) acc)))))
Alternatively, you can solve this problem using string operations:
(define char-zero (char->integer #\0))
(define (char->digit c)
(- (char->integer c) char-zero))
(define (number->list num)
(map char->digit
(string->list (number->string num))))
This can be compressed into a single function, but I believe it's easier to understand if we split the problem in subparts as above.
(define (number->list num)
(map (lambda (c) (- (char->integer c) (char->integer #\0)))
(string->list
(number->string num))))
Anyway, the results are as expected:
(number->list 34109)
> '(3 4 1 0 9)
Something like this:
(define (num2list-helper num lst)
(cond ((< num 10) (cons num lst))
(else (num2list-helper (floor (/ num 10)) (cons (modulo num 10) lst)))))
(define (num2list num)
(num2list-helper num '()))
(num2list 1432)
As itsbruce commented you can hide helper function inside main one:
(define (num2list num)
(define (num2list-helper num lst)
(cond ((< num 10) (cons num lst))
(else (num2list-helper (floor (/ num 10)) (cons (modulo num 10) lst)))))
(num2list-helper num '()))
(num2list 1432)
to be continued...
I'm not a fan of manual looping, so here's a solution based on unfold (load SRFI 1 and SRFI 26 first):
(define (digits n)
(unfold-right zero? (cut modulo <> 10) (cut quotient <> 10) n))
This returns an empty list for 0, though. If you want it to return (0) instead, we add a special case:
(define (digits n)
(case n
((0) '(0))
(else (unfold-right zero? (cut modulo <> 10) (cut quotient <> 10) n))))
Of course, you can generalise this for other bases. Here, I implement this using optional arguments, so if you don't specify the base, it defaults to 10:
(define (digits n (base 10))
(case n
((0) '(0))
(else (unfold-right zero? (cut modulo <> base) (cut quotient <> base) n))))
Different Scheme implementations use different syntaxes for optional arguments; the above uses Racket-style (and/or SRFI 89-style) syntax.

Scheme: recursion and lists

I've been trying to learn some programming on my own by working through the textbook How to Design Programs for Scheme. I've gotten through everything until now. Here's the problem:
9.5.5 Develop the function convert. It consumes a list of digits and
produces the corresponding number. The
first digit is the least significant,
and so on.
Following the first few steps, from data analysis to template, I end
up with this, the bare bones of a program:
;; A list-of-numbers is either 1. an empty list, empty, or 2. (cons n
lon) where n is a number and lon is a list of numbers
;; convert : lon -> number
;; to consume a lon and produce the corresponding number. The least
significant digit corresponds to the first number in the list, and so
on.
;; (= (convert (cons 1 (cons 9 (cons 10 (cons 99 empty))))) 991091)
(define (convert lon)
(cond
[(empty? lon)...]
[(cons? lon)...(first lon)...(convert (rest lon))...]))
How do I get past this stage to, as the book has it, "combining values"?
The one way I think could work is if I multiplied the first value by
10 to the power of the value's significance in the total number, e.g.,
(cons 1 (cons 9 empty)) => 1 * 10^(SIGNIFICANCE), where LEAST
SIGNIFICANCE would be 0. Using my limited understanding of
programming, I figure that requires some counter, where n increases by
one every time the function, in a manner of speaking, is called
recursively. But that looks to me to be an attempt to run two
recursions at the same time. Because expressions are evaluated
sequentially (obviously), you can't call the counter function as you
call the convert function.
So, can anyone help me solve this problem? I would prefer if you
solved this using natural recursion and the CONStructor for lists and
not lambda or other ideas the book hasn't addressed yet.
Thanks!
You don't need to do exponentiation - simple multiplication will do just fine.
(define (convert digits)
(cond
((empty? digits) 0)
(else (+ (* 10 (convert (rest digits))) (first digits)))
)
)
(convert '(1 2 3 4 5 6))
Or, another way of thinking about it:
(define (convert digits)
(convert-helper digits 1 0)
)
(define (convert-helper digits multiplier sofar)
(cond
((empty? digits) sofar)
(else
(convert-helper
(rest digits)
(* 10 multiplier)
(+ (* multiplier (first digits)) sofar)
)
)
)
)
(convert '(1 2 3 4 5 6))
Here's a tail recursive version:
(define (convert lon)
(let rec ((i 0)
(n 0)
(lon lon))
(cond ((empty? lon) n)
(else (rec (+ i 1)
(+ n (* (first lon) (expt 10 i)))
(rest lon))))))