Add rainbow test script
This commit is contained in:
parent
e4c6e42efb
commit
2acd572e8e
37
Rainbow/rainbow.js
Normal file
37
Rainbow/rainbow.js
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
// Approximate racket functions
|
||||||
|
function circle(color) {
|
||||||
|
print(`${color} circle`)
|
||||||
|
}
|
||||||
|
function square(color) {
|
||||||
|
print(`${color} square`)
|
||||||
|
}
|
||||||
|
function print(shape) {
|
||||||
|
console.log(shape)
|
||||||
|
}
|
||||||
|
// Cuz javascript doesn't have functional primitives
|
||||||
|
function first(list) {
|
||||||
|
return list[0]
|
||||||
|
}
|
||||||
|
function rest(list) {
|
||||||
|
return list.slice(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to cycle through the functions
|
||||||
|
function cycle(list) {
|
||||||
|
return rest(list).concat(first(list))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The actual function
|
||||||
|
function rainbow(...functions) {
|
||||||
|
let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
|
||||||
|
function rainbowRecursive(functions, colors) {
|
||||||
|
if (colors.length === 0) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
first(functions)(first(colors))
|
||||||
|
rainbowRecursive(cycle(functions), rest(colors))
|
||||||
|
}
|
||||||
|
rainbowRecursive(functions, colors)
|
||||||
|
}
|
||||||
|
|
||||||
|
rainbow(circle, square)
|
17
Rainbow/rainbow.rkt
Normal file
17
Rainbow/rainbow.rkt
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
#lang racket
|
||||||
|
(require pict)
|
||||||
|
(require pict/color)
|
||||||
|
; The actual function
|
||||||
|
(define (rainbow . shapes)
|
||||||
|
(define colors (list red orange yellow green blue purple))
|
||||||
|
(define (cycle lst) (append (rest lst) (list (first lst))))
|
||||||
|
(define (rainbow-recursive shapes colors)
|
||||||
|
(cond
|
||||||
|
[(empty? colors) (void)]
|
||||||
|
[(print((first colors) (first shapes)))
|
||||||
|
(rainbow-recursive (cycle shapes) (rest colors))]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
(rainbow-recursive shapes colors))
|
||||||
|
; Example usage
|
||||||
|
(rainbow (filled-rectangle 25 25) (filled-ellipse 25 25))
|
Loading…
Reference in New Issue
Block a user