Reputation: 47101
Like this:
> (my-append (list 1 2) 3)
'(1 2 3)
I know append
in racket
is actually to concatenate two list.
And cons
just add an element to the head of a list instead of tail
Does anyone have ideas about this?
Upvotes: 2
Views: 395
Reputation: 12033
If you're in Racket, you probably want to look into the growable vector library (data/gvector). This provides a container type that supports many of the features you're used to with Python's growable lists.
Example:
#lang racket
(require data/gvector)
(define lst (gvector 1 2))
(gvector-add! lst 3)
(for ([elt lst]) (printf "I see: ~s\n" elt))
Otherwise, your question ends up reducing to: how do I make immutable linked lists work like mutable sequentially-allocated arrays? And that's not going to work well: data types are different for different reasons.
Upvotes: 3
Reputation: 236170
In Pyton, the append()
method modifies the list in-place:
lst = [1, 2]
lst.append(3)
lst
=> [1, 2, 3]
Racket's lists are immutable by default, the closest thing to an in-place append()
requires you to use mutable lists, and you have to pack the element to be appended in a list of its own:
(require scheme/mpair)
(define lst (mlist 1 2))
(mappend! lst (mlist 3))
lst
=> (mlist 1 2 3)
Notice that using immutable lists with the append
procedure will produce a new list, leaving the original list untouched - so it wouldn't be "like Python":
(define lst (list 1 2))
(append lst (list 3)) ; this returns the new list '(1 2 3)
lst
=> (list 1 2)
In fact, Scheme's append
procedure behaves just like Python's +
operation between lists:
lst = [1, 2]
lst + [3] # this returns the new list [1, 2, 3]
lst
=> [1, 2]
Come to think of it, Python's append()
might have a misleading name - in most functional programming languages, the append operation is always defined between two lists, whereas in Python it's an operation between a list and an element. Maybe add()
would have been a better name, like Java's add()
operation of the List
interface.
Upvotes: 5
Reputation: 8135
I don't know what you mean with "append like python", but if all you want is to insert a new element at the end of the list, you may use this:
(define (my-append lst el)
(append lst (list el)))
Upvotes: 0