3

I am trying to get a random string from a list of strings in scheme. Example List ( "this" "that" "today" "yesterday") So based on length of the list a random number is created and that word is output. But keep getting error!

I tried it like this:

;; produces random number that should be input to the random-function

(define (random-num list)

(random-function ((random (length (list))) list)))

;; loops the number of times till random number is 0 and outputs the list value

(define (random-function num list )
  (cond 
    [(zero? num) (car list)]
    [else (random-function (- num 1) (cdr list))]))

Error:

procedure application: expected procedure, given: 
("this" "that" "today" "yesterday") (no arguments)

When I try to do :

(random-function (random (length list)) 

on the console I get a random number.

Do not understand why it is crashing here when done inside my program???

Could I do this in a better way rather than looping so many times. In Java I would have used an array and given the position directly. Anyway to do it in scheme too ?

Majora320
  • 1,321
  • 1
  • 13
  • 33
JJunior
  • 2,831
  • 16
  • 56
  • 66

1 Answers1

10
(define (random-element list)
  (list-ref list (random (length list))))
Eli Barzilay
  • 29,301
  • 3
  • 67
  • 110
  • u r awesome!! list-ref is awesome!! seems better than arrays now :) – JJunior Nov 13 '10 at 21:47
  • 2
    Well, vectors are still better if you have really big lists, otherwise the difference is negligible. – Eli Barzilay Nov 13 '10 at 22:10
  • 1
    Vectors are better because you can instantly jump to element `n`, whereas lists you have to start from the beginning and find your way to element `n`. – erjiang Nov 14 '10 at 03:12
  • 2
    Yes, vectors are random access -- but people often overestimate the difference, and end up with vectors and inconvenient code too early. – Eli Barzilay Nov 14 '10 at 17:29
  • And then there is also such a beast as a random access list,. – WorBlux May 30 '16 at 02:28