Additional structure field

I was looking for documentation for Racket (a non-typed language) and was unable to decide whether it is possible to have optional arguments for an immutable structure. I would like to be able to:

(struct q-a-website (name interest-value #syntax? some-optional-field))
... (q-a-website "stack-overflow" 42 "My name is Jon Skeet") ...
... (q-a-website "quora" -inf.0) ...

This pseudo-example #syntax?is just a placeholder, where I suspect that some special syntax may reside to make the next field optional. Is there a way to make your everyday, immutable, running structure structural parameters in a basic Racket?

Explanation: If a structure is created without an optional parameter, it is populated with a default value that must be specified at creation time. In this case, this information should be contained within a block (possibly poorly named) #syntax?.

(Note: I have reservations about including the tag structin this question, as it mentions the C family of languages ​​that Racket does not belong to ...)

+4
source share
2 answers

I think the easiest way to do what you want is to create a “constructor” that has an optional argument, for example:

#lang racket

(struct q-a-website (name interest-value optional-field))

;; make a q-a-website
(define (make-q-a-website name interest-value [optional-field #f])
  (q-a-website name interest-value optional-field))

;; try making it with and without the optional argument:
(make-q-a-website "stack-overflow" 42 "My name is Jon Skeet")
(make-q-a-website "quora" -inf.0)

Racket also has a full-blown class system, with ... almost everything you can imagine. For this use, I think I would just do it like this.

+5
source

If the default value for an optional field makes sense, then I would do what John suggested in my comment - just define a custom constructor:

(struct s (a b opt))

(define (make-s a b [opt #f])
  (s a b opt))

(make-s "a" "b")
(make-s "a" "b" "opt")

, opt N/A, struct s: , :

(struct general (a b))
(struct special general (opt))

(define g (general "a" "b"))
(define s (special "a" "b" "opt"))

, / general, general special :

(general? g) ; #t
(general? s) ; #t

, special, :

(special? g) ; #f
(special? s) ; #t

, , "is-a" ( " " ), , "special general".


, , racket/class.

+3

Source: https://habr.com/ru/post/1527991/


All Articles