Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

lisp change machine

Name: Anonymous 2015-09-19 12:52

dynamic programming mixed with HOFs. originally an exam question. brain on fire for an undergrad fuckwit like myself

(define (change amt coins)
(cond
((= amt 0) '(()))
((or (<= amt 0) (null? coins)) '())
(else
(fold-right (lambda (a b) (append a b))
'()
(map
(lambda (n)
(map
(lambda (u)
(append (list n) u))
(change (- amt n)
(filter (lambda (k) (>= k n)) coins))))
coins)))))

;; -----------------------------------------------------------------------

(define (display-nl u)
(display u)
(newline))

(define display-elements
(lambda (u)
(map display-nl u)))

(define (demo r k)
(display-nl '-----------------------------)
(display r) (display ';;) (display k) (newline)
(display-nl '=============================)
(display-elements (change r k))
(display-nl '-----------------------------)
(newline))

;; -----------------------------------------------------------------------

(newline)

(demo 5 '(1 2 5))
(demo 13 '(1 3 5 7))
$ ./lisp <change.lisp

Loaded `prefix.txt'

-----------------------------
5;;(1 2 5)
=============================
(1 1 1 1 1)
(1 1 1 2)
(1 2 2)
(5)
-----------------------------

-----------------------------
13;;(1 3 5 7)
=============================
(1 1 1 1 1 1 1 1 1 1 1 1 1)
(1 1 1 1 1 1 1 1 1 1 3)
(1 1 1 1 1 1 1 1 5)
(1 1 1 1 1 1 1 3 3)
(1 1 1 1 1 1 7)
(1 1 1 1 1 3 5)
(1 1 1 1 3 3 3)
(1 1 1 3 7)
(1 1 1 5 5)
(1 1 3 3 5)
(1 3 3 3 3)
(1 5 7)
(3 3 7)
(3 5 5)
-----------------------------

Name: OP 2015-09-23 12:28

>>22

thank you but it doesn't work

# #use "change2.ml";;
val change : int -> int list -> int list list = <fun>
# change 5 [1;2;5];;
- : int list list = []


I changed the first case to a [[]] and it still doesn't work:

# change 5 [1;2];;
- : int list list =
[[1; 1; 1; 1; 1]; [1; 1; 1; 1; 2]; [1; 1; 1; 2]; [1; 1; 2; 2]; [1; 2; 2];
[2; 2; 2]]


# change 1 [1;2];;
- : int list list = [[1]; [2]]


it's been a while since i touched the code but i think the <= 0 check was there for a reason that has to do with this

>>20
maybe i should use more descriptive names for the lambda bindings, then it would be much more readable

>>19
i was being a bit paranoid/stupid, append takes arbitrary amount of arguments so i wasn't sure i could use it with foldr which expects a function that takes exactly two arguments. but you're right, it works when i just do
...
(fold-right append
...

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List