;;;; Copyright (C) 2020 Julien Lepiller ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 3 of the License, or (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public ;;;; License along with this library; if not, write to the Free Software ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;;;; (define-module (jsonld flattening) #:use-module (jsonld generate-blank-node-identifier) #:use-module (jsonld json) #:use-module (jsonld node-map-generation) #:export (flattening)) (define* (flattening element #:key ordered?) ;; 1 (let ((node-map `(("@default" . ()))) (default-graph '()) (node-map-generation (get-node-map-generation (get-generate-blank-node-identifier)))) ;; 2 (set! node-map (assoc-ref (node-map-generation element node-map) "node-map")) ;; 3 (set! default-graph (assoc-ref node-map "@default")) ;; 4 (for-each-pair (lambda (graph-name graph) (unless (equal? graph-name "@default") ;; 4.1 (unless (json-has-key? default-graph graph-name) (set! default-graph (alist-set default-graph graph-name `(("@id" . ,graph-name))))) ;; 4.2 (let ((entry (assoc-ref default-graph graph-name)) (graph-entry '())) ;; 4.3 (set! entry (alist-set entry "@graph" '())) ;; 4.4 (for-each-pair (lambda (id node) (unless (null? (filter (lambda (kv) (not (equal? (car kv) "@id"))) node)) (set! graph-entry (cons node graph-entry)))) (if ordered? (alist-sort-by-key graph) graph)) (set! entry (alist-set entry "@graph" (list->array 1 (reverse graph-entry)))) (set! default-graph (alist-set default-graph graph-name entry))))) (if ordered? (alist-sort-by-key node-map) node-map)) ;; 5 (let ((flattened '())) ;; 6 (for-each-pair (lambda (id node) (unless (null? (filter (lambda (kv) (not (equal? (car kv) "@id"))) node)) (set! flattened (cons node flattened)))) (if ordered? (alist-sort-by-key default-graph) default-graph)) ;; 7 (list->array 1 (reverse flattened)))))