VansFannel
VansFannel

Reputation: 45921

How to declare a variable inside a procedure in Scheme: define: not allowed in an expression context

I'm a C# programmer learning Scheme, and I have a lot of troubles, because I don't understand Scheme.

I have write it this code with a lot of help:

#lang racket

(define sort-asc-by-second
  (lambda (lst)
    (sort lst
          (lambda (x y) (< (cdr x) (cdr y))))))

(define sum
  (lambda (lst)
    (apply + (map cdr lst))
  )
)

(define my-function
  (lambda (lst)
   (
    (define sorted (sort-asc-by-second lst))
    (define suma (sum lst))
    (define lista (map (lambda (p) (cons (car p) (/ (cdr p) suma)))))
   ))
)

But I get the following error:

define: not allowed in an expression context in: (define sorted (sort-asc-by-second lst))

At this line:

(define sorted (sort-asc-by-second lst))

How can I declare a variable? Maybe, the problem here is that I'm a C# programmer and I don't understand Scheme.

Upvotes: 1

Views: 582

Answers (2)

John Clements
John Clements

Reputation: 17203

I think it's going to be very important for you to follow the steps of the Design Recipe. In this case:

  • write a signature: the types that the function takes in and returns.
  • Write test cases, using check-equal?.
  • Follow the template for the data that you've chosen.

Put differently (and perhaps a bit more bluntly): stop wandering. Start designing!

Upvotes: 2

merlyn
merlyn

Reputation: 2361

I have no idea what this program is trying to do, but the current error you are seeing is due to an extra pair of brackets.

(define my-function
  (lambda (lst)

    (define sorted (sort-asc-by-second lst))
    (define suma (sum lst))
    (define lista (map (lambda (p) (cons (car p) (/ (cdr p) suma)))))
    )
  )

Upvotes: 2

Related Questions