简体   繁体   中英

Typed racket, changing a single component of a list

Is there a way to change a single value of a list, called by list-ref, to a different value in typed Racket?

Like: (Change (list-ref (list 1 2 2) 0) 4) Would output: (list 4 2 2)

(: duck : (Listof Integer) -> (Listof Integer))
(define (duck n)
  (match n
    [' () ' ()]
    [(cons x r)
     (cond
       [(= x (list-ref n 1))
        (cons 4 (duck r))]
       [else (cons x (duck r))])]))

I wrote this recursive function in an attempt to do so, but it doesn't work. My logic is as follows: If x is (list-ref n 1) then change x to 4.

Any help is much appreciated.

list-set from unstable/list does what you want:

#lang typed/racket/base
(require/typed unstable/list
               [list-set (All (a) (Listof a) Natural a -> (Listof a))])
(list-set (list 1 2 2) 0 4)
; '(4 2 2)

Update:

The latest version of racket now provides list-set from typed/racket :

#lang typed/racket
(list-set (list 1 2 2) 0 4)

Or if you wanted to use typed/racket/base :

#lang typed/racket/base
(require racket/list)
(list-set (list 1 2 2) 0 4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM