exercies 2 :
1. my-reverse that reverse the order of list items. (Function reverse is pre-defined.)
要求用尾递归写一个将列表逆序的函数。
答案如下:
-
cat tail_reverse.scm
-
#! /usr/bin/env guile -s
-
!#
-
-
(define (my-reverse ls)
-
(my-reverse-rec ls ()))
-
-
(define (my-reverse-rec ls0 ls1)
-
(if (null? ls0)
-
ls1
-
(my-reverse rec (cdr ls0) (cons (car ls0) ls1))))
我实验了下这个代码会报错。
-
guile
-
GNU Guile 2.0.13
-
Copyright (C) 1995-2016 Free Software Foundation, Inc.
-
-
Guile comes with ABSOLUTELY NO WARRANTY; for details type `,show w'.
-
This program is free software, and you are welcome to redistribute it
-
under certain conditions; type `,show c' for details.
-
-
Enter `,help' for help.
-
scheme@(guile-user)> (load "tail_reverse.scm")
-
;;; note: auto-compilation is enabled, set GUILE_AUTO_COMPILE=0
-
;;; or pass the --no-auto-compile argument to disable.
-
;;; compiling /usr/local/src/scheme/tail_reverse.scm
-
;;; WARNING: compilation of /usr/local/src/scheme/tail_reverse.scm failed:
-
;;; ERROR: Syntax error:
-
;;; unknown location: unexpected syntax in form ()
-
ice-9/boot-9.scm:703:29: In procedure map:
-
ice-9/boot-9.scm:703:29: Syntax error:
-
unknown location: unexpected syntax in form ()
-
-
Entering a new prompt. Type `,bt' for a backtrace or `,q
代码修改下,将第六行中的()修改为空列表, '().
-
#! /usr/bin/env guile -s
-
!#
-
-
(define (my-reverse ls)
-
(my-reverse-rec ls '())
-
-
(define (my-reverse-rec ls0 ls1)
-
(if (null? ls0)
-
ls1
-
(my-reverse-rec (cdr ls0) (cons (car ls0) ls1))))
-
guile
-
(load "tail_reverse.scm")
-
,binding
my-reverse-rec #>
my-reverse #>
%module-public-interface #>
-
(my-reverse (list 1 2 3 4 5))
$1 = (5 4 3 2 1)
阅读(1060) | 评论(0) | 转发(0) |