Ooops, sent it to the wrong address. ---------- Forwarded message ---------- From: Artyom Shalkhakov <[email protected]> Date: 2009/9/25 Subject: Re: "Schema" for data structures To: clojure group <[email protected]>
Hello Miron, > is there a way to check if a data structure complies to a given > schema? (e.g. people is a vector of persons). > > I'm using C# a lot and maybe the static typing has changed the way I > think. I feel like adding "type checks" in unit tests and being able > to say something like: > > (is-type (people (vector person))) > > sounds like a neat way to check types (I know 'vector' is a 'taken' > name, I'm just trying to illustrate the kind of syntax I'm thinking > about). The degree of typing can be varied (i.e. a person is any map > with a :name key, or any map with only a :name key, or any map with a > :name key which is nil or string etc.) You might be looking for something akin to contracts of PLT Scheme: http://pre.plt-scheme.org/docs/html/guide/contracts.html there are also "define-type" and "type-case" macros (again for Scheme, specifically PLAI language, but I guess they can be translated to Clojure easily), which I find very handy. Can't post the link ATM because PLaneT seems to be down or something though. Here's an example of define-type/type-case in Scheme: (require (planet "main.ss" ("plai" "plai.plt" 1 3))) ;; arithmetical expressions (define-type AE ;; distinguish various cases, ;; very much like a union in C but with an explicit "type" tag ;; (one of num, plus, sub) ;; not we enforce a contract on each member (num (n number?)) (plus (l AE?) (r AE?)) (sub (l AE?) (r AE?))) (provide/contract [interp (-> AE? number?)]) ;; interpret an arithmetical expression yielding a number (define (interp exp) ;; type-case is very much like a "case ... of" in Haskell/ML (type-case AE exp (num (n) n) (plus (l r) (+ (interp l) (interp r))) (sub (l r) (- (interp l) (interp r))))) Contracts work only between module boundaries though. Cheers, Artyom Shalkhakov. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to [email protected] Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---
