Up: Учебник по Scheme [Contents][Index]
Guix использует Guile имплементацию Scheme. Чтобы опробовать язык,
установите его с помощью guix install guile
и запустите
REPL—сокращение от read-eval-print loop—запустив guile
в командной строке.
Кроме того, вы можете запускать guix shell guile -- guile
, если у вас
нет Guile в профиле пользователя.
В следующих примерах строки показывают то, что вы будете вводить в REPL; строки, начинающиеся с “⇒”, показывают вычислительные результаты, в то время как строки, начинающиеся с “-|”, показывают напечатанные вещи. See Using Guile Interactively in GNU Guile Reference Manual, для более подробной информации о REPL.
#true
и #false
(сокращенно #t
и
#f
) представляет логические ‘true” and “false” соответственно.
Примеры допустимых выражений:
"Hello World!" ⇒ "Hello World!" 17 ⇒ 17 (display (string-append "Hello " "Guix" "\n")) -| Hello Guix! ⇒ #<unspecified>
lambda
:
Вышеприведенная процедура возвращает квадрат его аргумента. Поскольку все
это выражение, lambda
выражение возвращает анонимную процедуру,
которая в свою очередь может быть применена к аргументу:
((lambda (x) (* x x)) 3) ⇒ 9
Процедуры - это обычные значения, такие как числа, строки, логические значения и так далее.
define
:
(define a 3) (define square (lambda (x) (* x x))) (square a) ⇒ 9
(define (square x) (* x x))
list
:
(list 2 a 5 7) ⇒ (2 3 5 7)
(srfi srfi-1)
для
создания и обработки списков (see (GNU Guile
Reference Manual)list processing). Вот некоторые из наиболее полезных в работе:
(use-modules (srfi srfi-1)) ;import list processing procedures (append (list 1 2) (list 3 4)) ⇒ (1 2 3 4) (map (lambda (x) (* x x)) (list 1 2 3 4)) ⇒ (1 4 9 16) (delete 3 (list 1 2 3 4)) ⇒ (1 2 4) (filter odd? (list 1 2 3 4)) ⇒ (1 3) (remove even? (list 1 2 3 4)) ⇒ (1 3) (find number? (list "a" 42 "b")) ⇒ 42
Обратите внимание, что первый аргумент map
, filter
,
remove
и find
это процедура!
'(display (string-append "Hello " "Guix" "\n")) ⇒ (display (string-append "Hello " "Guix" "\n")) '(2 a 5 7) ⇒ (2 a 5 7)
quasiquote
(`
, обратная кавычка) запрещает вычисление
выражения в круглых скобках, пока unquote
(,
, запятая)
повторно его не включит. Таким образом, он обеспечивает нам четкий контроль
над тем, что вычисляется и что нет.
`(2 a 5 7 (2 ,a 5 ,(+ a 4))) ⇒ (2 a 5 7 (2 3 5 7))
Обратите внимание, что приведенный выше результат - это смешанный список
элементов: чисел, символов (здесь a
), а последний элемент сам по себе
список.
quasiquote
и unquote
: #~
(или gexp
) и #$
(или ungexp
). Они позволяют вам stage code for later
execution.
Например, вы столкнетесь с gexps в некоторых определениях пакетов, где они предоставляют код для выполнения во время процесса сборки пакетов. Они выглядят следующим образом:
(use-modules (guix gexp) ;so we can write gexps (gnu packages base)) ;for 'coreutils' ;; Below is a G-expression representing staged code. #~(begin ;; Invoke 'ls' from the package defined by the 'coreutils' ;; variable. (system* #$(file-append coreutils "/bin/ls") "-l") ;; Create this package's output directory. (mkdir #$output))
See G-Expressions in GNU Guix Reference Manual, for more on gexps.
let
(see Local Bindings in GNU Guile Reference Manual):
(define x 10) (let ((x 2) (y 3)) (list x y)) ⇒ (2 3) x ⇒ 10 y error→ In procedure module-lookup: Unbound variable: y
Use let*
to allow later variable declarations to refer to earlier
definitions.
#:
(hash, colon) followed by
alphanumeric characters: #:like-this
. See Keywords in GNU
Guile Reference Manual.
%
is typically used for read-only global variables in
the build stage. Note that it is merely a convention, like _
in C.
Scheme treats %
exactly the same as any other letter.
define-module
(see Creating Guile
Modules in GNU Guile Reference Manual). For instance
(define-module (guix build-system ruby)
#:use-module (guix store)
#:export (ruby-build
ruby-build-system))
defines the module guix build-system ruby
which must be located in
guix/build-system/ruby.scm somewhere in the Guile load path. It
depends on the (guix store)
module and it exports two variables,
ruby-build
and ruby-build-system
.
See Package Modules in GNU Guix Reference Manual, for info on modules that define packages.
Больше информации: Scheme is a language that has been widely used to teach programming and you’ll find plenty of material using it as a vehicle. Here’s a selection of documents to learn more about Scheme:
- A Scheme Primer, by Christine Lemmer-Webber and the Spritely Institute.
- Scheme at a Glance, by Steve Litt.
- Structure and Interpretation of Computer Programs, by Harold Abelson and Gerald Jay Sussman, with Julie Sussman. Colloquially known as “SICP”, this book is a reference.
You can also install it and read it from your computer:
guix install sicp info-reader info sicpYou’ll find more books, tutorials and other resources at https://schemers.org/.
Up: Учебник по Scheme [Contents][Index]