Cool Code

From Sch3m3rs Stuph

This page is for interesting bits and bobbles of coding:

Format is:

        Name for code
        Code
        What it does



Display List W/ line-breaks

 (define (displayx x)
   (begin
     (display x)
     (newline)))
  (define (for-each-disp a-list) 
    (for-each displayx a-list))

When given a list it takes each item displays it in the interactions window with each piece separated with a line break.

For Example When given the definition

   (define MARY (list "Mary had a little lamb," "Its fleece was white as snow;"
    "And everywhere that Mary went," "The lamb was sure to go."
    "He followed her to school one day;" "That was against the rule;"
    "It made the children laugh and play;" "To see a lamb at school."
    "And so the teacher turned it out,"
    "But still it lingered near," "And waited patiently about"
    "Till Mary did appear." "Why does the lamb love Mary so?"
    "The eager children cry;" "Why, Mary loves the lamb, you know," "The teacher did reply."))

The function:

   (for-each-disp MARY)

Returns:

   Mary had a little lamb,
   Its fleece was white as snow;
   And everywhere that Mary went,
   The lamb was sure to go.
   He followed her to school one day;
   That was against the rule;
   It made the children laugh and play;
   To see a lamb at school.
   And so the teacher turned it out,
   But still it lingered near,
   And waited patiently about
   Till Mary did appear.
   Why does the lamb love Mary so?
   The eager children cry;
   Why, Mary loves the lamb, you know,
   The teacher did reply.

List Pick Random

   (define (list-pick-random ls)
     (list-ref ls (random (length ls))))

When Given a list it randomly picks one of the items contained in the list.


Personal tools