我正在读取.csv文件,并且是
django
将其转换为struct。但是,所有字段都是字符串,是否有一些优雅的方法可以在例如上强制(define-struct my-struct (id name))
(apply my-struct '("5" "Tomas"))
(string? (my-struct-id (apply my-struct '("5" "Tomas"))))
转换。 string->number
字段?
非常感谢。
答案 0 :(得分:3)
我看到有两个选择。第一个是最简单的,使用自定义构造函数:
; Option 1: Make a dedicated constructor that
; handles the conversion.
(struct my-struct (id name) #:transparent)
(define (create-struct id name)
(my-struct (string->number id) name))
第二种选择是(ab)使用警卫:
; Option 2: Use a guard
(define (converter id name the-struct-name)
(values (string->number id) name))
(struct my-second-struct (id name) #:guard converter #:transparent)
(apply my-second-struct '("5" "Tomas"))
答案 1 :(得分:2)
要完成soegaard的答案,如果您提供结构并在其他模块中使用它,则还可以添加合同以防止错误使用:
#lang racket/base
(require racket/contract)
(provide (contract-out
[struct person ((id number?) (name string?))]))
(struct person (id name))
> (require my-module/person)
> (person 42 "Margaret")
#<person>
> (person "haxxor" 1337)
; person: contract violation
; expected: number?
; given: "haxxor"
; in: the 1st argument of
; (-> number? string? person?)
在此处查看完整的文档:https://docs.racket-lang.org/guide/contracts-struct.html#(part._contracts-define-struct)