Question

I am working in Racket with no experience.

I am going to write what I wanted to write in C:

void function(int array[]){
    printf("%i total has been rolled from rolls %i and %i.\n", array[0], array[1], array[2]);
}

As you can see it is just a basic function that will print out the values of a list I want to pass in to my function. I do not know how to pass parameters (is this the correct terminology?) in Racket. I am trying to pass in a list with the format: (sum num1 num2) or I can pass it in as ((sum) num1 num2) if that makes it easier.

This is my current function:

(define (throw-value) 
    (list (list(list-sum (dice-rolls))) (car(dice-rolls)) (car(dice-rolls))))

Where dice-rolls is my parameter list that I desire to use.

Any suggestions? Code segments would be GREAT! Thanks.

Was it helpful?

Solution

Answering the question of how to pass parameters in Racket - just declare them after the function's name, and be careful with the parentheses (there are several erroneous parentheses in your code). I believe you were aiming for something like this:

(define (throw-value dice-rolls)
  (list (list-sum dice-rolls) (car dice-rolls) (car dice-rolls)))

The above will return a list in the format (sum num1 num2), be aware that num1 and num2 will be the same number, because in both cases you're taking the first element of the list. Now, for the rest of the question - in Racket, a direct translation of the C code in the question will look like this:

(define (function vec)
  (printf "~a total has been rolled from rolls ~a and ~a.~n"
          (vector-ref vec 0)
          (vector-ref vec 1)
          (vector-ref vec 2)))

(define vec (vector 1 2 3)) ; `vec` is a vector
(function vec)
=> 1 total has been rolled from rolls 2 and 3.

Although the linked list is the standard data structure in Lisp-based programming languages, whenever you need to efficiently access data given an index it's better to use a vector as shown above. If for some reason you really have to use a list you can do so, albeit less efficiently (linked lists are not optimized for index-based access):

(define (function lst)
  (printf "~a total has been rolled from rolls ~a and ~a.~n"
          (list-ref lst 0)
          (list-ref lst 1)
          (list-ref lst 2)))

(define lst (list 1 2 3)) ; `lst` is a singly-linked list
(function lst)
=> 1 total has been rolled from rolls 2 and 3.

OTHER TIPS

Since you are using #!Racket and not Scheme, why not use struct

(struct dice (total min max) #:transparent) 

(define (print-dice d)
  (printf "~a total has been rolled from rolls ~a and ~a.~n"
          (dice-total d)
          (dice-min d)
          (dice-max d)))

(print-dice (dice 10 2 6))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top