Racket-如何更改结构的属性值
我有以下结构:Racket-如何更改结构的属性值,racket,Racket,我有以下结构: (define-struct my-struct (label value)) 我想更改列表中所有项目的属性值。我想在所有项目中设置值2 (define (change-value mylist priority) ( cond [( empty? mylist) mylist] [else ( cons ((struct-copy my-struct (first mylist) [value 2]) ) (change-value (rest myli
(define-struct my-struct (label value))
我想更改列表中所有项目的属性值。我想在所有项目中设置值2
(define (change-value mylist priority)
( cond
[( empty? mylist) mylist]
[else ( cons ((struct-copy my-struct (first mylist) [value 2]) ) (change-value (rest mylist) value) )]))
)
我试图使用struct copy
,但出现以下错误:
struct copy:未定义此函数
知道我为什么会犯这个错误吗?我应该导入任何库吗?还不完全清楚您希望代码做什么。下面是一个遍历“my struct”列表并将所有“value”属性设置为2的版本:
#lang racket
(define-struct my-struct (label value) #:transparent)
(define (change-value mylist)
(for/fold ([result '()])
([s (in-list mylist)])
(cons (struct-copy my-struct s [value 2]) result)))
如果我运行它,我会得到:
> (define l (list (my-struct 1 3) (my-struct 4 6) (my-struct 8 7)))
> l
(list (my-struct 1 3) (my-struct 4 6) (my-struct 8 7))
>
> (change-value l)
(list (my-struct 8 2) (my-struct 4 2) (my-struct 1 2))
您可以通过构建另一个结构来更改结构,例如,如果我们想在结构内部切换元素
#lang racket
(define-struct s (s1 s2) #:transparent #:mutable)
(define (switch st)
(s (s-s2 st) (s-s1 st)))
;;; TEST
(switch (s 1 2)) ; (s 2 1)
#lang racket
(define-struct my-struct (label value) #:transparent #:mutable)
(define (change-value->2 lst-of-struct new-value)
(map (λ (s) (my-struct (my-struct-label s) new-value))
lst-of-struct))
;;; TEST
(change-value->2 (list (my-struct 'a 1) (my-struct 'b 1) (my-struct 'c 1))
2)
因此,在这里,我们可以使用map
在struct中每秒钟更改一个元素
#lang racket
(define-struct s (s1 s2) #:transparent #:mutable)
(define (switch st)
(s (s-s2 st) (s-s1 st)))
;;; TEST
(switch (s 1 2)) ; (s 2 1)
#lang racket
(define-struct my-struct (label value) #:transparent #:mutable)
(define (change-value->2 lst-of-struct new-value)
(map (λ (s) (my-struct (my-struct-label s) new-value))
lst-of-struct))
;;; TEST
(change-value->2 (list (my-struct 'a 1) (my-struct 'b 1) (my-struct 'c 1))
2)
最后,我通过makemystruct生成一个新的结构。使用struct copy时,我遇到了一个错误。无法识别命令结构副本您使用的语言是什么
struct copy
应该在正常情况下可用,所以您是否使用其他语言,如初级学生语言、中级学生语言或其他更严格的语言?好的,是的,我使用的是学生语言。此版本中是否不包含此功能?