fromrdf.scm
| 1 | ;;;; Copyright (C) 2020 Julien Lepiller <julien@lepiller.eu> |
| 2 | ;;;; |
| 3 | ;;;; This library is free software; you can redistribute it and/or |
| 4 | ;;;; modify it under the terms of the GNU Lesser General Public |
| 5 | ;;;; License as published by the Free Software Foundation; either |
| 6 | ;;;; version 3 of the License, or (at your option) any later version. |
| 7 | ;;;; |
| 8 | ;;;; This library is distributed in the hope that it will be useful, |
| 9 | ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 | ;;;; Lesser General Public License for more details. |
| 12 | ;;;; |
| 13 | ;;;; You should have received a copy of the GNU Lesser General Public |
| 14 | ;;;; License along with this library; if not, write to the Free Software |
| 15 | ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 16 | ;;;; |
| 17 | |
| 18 | (define-module (turtle fromrdf) |
| 19 | #:use-module (ice-9 match) |
| 20 | #:use-module (ice-9 textual-ports) |
| 21 | #:use-module (iri iri) |
| 22 | #:use-module (srfi srfi-1) |
| 23 | #:use-module (srfi srfi-9) |
| 24 | #:use-module (rdf rdf) |
| 25 | #:export (rdf->turtle)) |
| 26 | |
| 27 | (define (turtle-escape str) |
| 28 | "Escape a string for writing it to a turtle document." |
| 29 | (list->string (append-map (lambda (c) |
| 30 | (match c |
| 31 | (#\\ (list #\\ #\\)) |
| 32 | (#\" (list #\\ #\")) |
| 33 | (#\newline (list #\\ #\n)) |
| 34 | (#\return (list #\\ #\r)) |
| 35 | (#\tab (list #\\ #\t)) |
| 36 | (#\backspace (list #\\ #\b)) |
| 37 | (_ (list c)))) |
| 38 | (string->list str)))) |
| 39 | |
| 40 | (define (node->turtle node) |
| 41 | (cond |
| 42 | ((blank-node? node) |
| 43 | (string-append "_:" (number->string node))) |
| 44 | ((rdf-datatype? node) |
| 45 | (string-append "<" (car (rdf-datatype-iris node)) ">")) |
| 46 | ((rdf-literal? node) |
| 47 | (string-append "\"" (turtle-escape (rdf-literal-lexical-form node)) "\"" |
| 48 | (if (rdf-literal-langtag node) |
| 49 | (string-append "@" (rdf-literal-langtag node)) |
| 50 | (let ((type (rdf-literal-type node))) |
| 51 | (string-append |
| 52 | "^^<" (if (rdf-datatype? type) |
| 53 | (car (rdf-datatype-iris type)) |
| 54 | type) |
| 55 | ">"))))) |
| 56 | ((string? node) |
| 57 | (string-append "<" node ">")))) |
| 58 | |
| 59 | (define (rdf->turtle g) |
| 60 | (string-join |
| 61 | (map |
| 62 | (match-lambda |
| 63 | (($ rdf-triple subject predicate object) |
| 64 | (format #f "~a ~a ~a ." |
| 65 | (node->turtle subject) |
| 66 | (node->turtle predicate) |
| 67 | (node->turtle object)))) |
| 68 | g) |
| 69 | "\n")) |
| 70 |