Friday 24 July 2020

(practical-python->racket 1.5 Lists)

The format on the section 1.5 Lists in Practical Python Programming is similar to the section on Strings. Again, I have created a single file, lists.rkt, that covers both the examples and exercises. 

Before starting on the noticeable differences (to me), a quick reminder to say that I'm in the process of learning Racket and my translations are highly likely not to be the best. If you can suggest better ones, please leave a comment.

The one big difference that I noticed is that lists are mutable in Python but immutable in Racket. (Though Racket does have a separate mutable list datatype.) That apart, there seemed to be less differences between Python and Racket Lists than there is between their strings.

Python has an insert method which allows an item to be inserted at specified point in the list. I was able to translate by using the Racket take and drop functions:
  Python
  names.insert(2, "Aretha"))
  Racket
  (append (take names 2) '("Aretha") (drop names 2))

As with Strings, Python supports supplying a negative index to indicate an index from the end of the list. This can be easily be emulated by using the length function to calculate the desired index. For lists, but not strings, Racket has the last function which makes it easy to get the last item in a list.

Translating in function required using Racket's index-of function and checking whether it returned a number or not.
Python
  'Elwood' in names
Racket
  (number? (index-of names "Elwood"))

It seems that it is only possible to sort lists in both Python and Racket if they have the same type of data.

Python:
>>> [1, "b", 3].sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'

Racket:
> (sort '(1 "b" 3) >)
; >: contract violation
;   expected: real?
;   given: "b"
;   argument position: 1st
; [,bt for context]

In summary, I found translating the contents of Lists quite a bit easier than I did with Strings.

Next up 1.6 Files

No comments: