Tomer
Tomer

Reputation: 559

can not use list functions on an input var - racket

well after building a whole function I got many problems and now I am breaking it down into small parts.

My func gets two vars one is a list and the other is a pair. When using (first var1) I get an error.

Here is the code:

#lang pl

    (define (maxMin list maxiMini)
      (if (null? maxiMini)
          (first list)
          2
      )
    )

Here is the error:

Type Checker: Polymorphic function `first' could not be applied to arguments:

Domains: (Listof a)

        (Pairof a (Listof b)) 

Arguments: Any

in: (first list)

While in this youtube tutorial at minute 1 and 10 seconds the professor uses the first function the same way as me and it does work there.

My guess is that Racket does not recognize myList as a list and sets it as "any" is this possible?

Upvotes: 0

Views: 435

Answers (1)

assefamaru
assefamaru

Reputation: 2789

Since you have a Type Checker error, I assume you're using either #lang typed/racket, or some variant of it.

If you look closely at the error itself, it is telling you that first is a polymorphic function, meaning that it can be applied to arguments of different types. Furthermore, the error also states the different types the function first expects under "Domains:", ie. its argument should either be (Listof a) or (Pairof a (Listof b)).

The problem is, you've not actually defined a type for your function maxMin. And if a type annotation is omitted, the inferred type is often Any. As a result, your function does not type-check, because first does not expect the type Any and that's what it is getting.

Since you stated

My func gets two vars one is a list and the other is a pair

consider the following type annotation for your function:

(: max-min (-> (Listof Any) (U Null (Pairof Any Any)) Any))
(define (max-min lst maxi-mini)
  (if (null? maxi-mini)
      (first lst)
      2))

which will type-check, and you can have:

(max-min '(1 2 3) '())
=> 1

Upvotes: 2

Related Questions