首页 > 代码库 > scheme 中的宏使用
scheme 中的宏使用
#lang scheme
( define-syntax my-when
( syntax-rules ()
[ ( _ pred body ... )
( if pred ( begin body ... ) ( void ) ) ] ) )
( my-when
( = 2 1 )
( display 1 )
( display 2 ) )
( define-syntax my-let
( syntax-rules ()
[ ( my-let ( [ var exp ] ... )
body ... )
( ( lambda ( var ... )
body ... ) exp ... ) ] ) )
( my-let
( [ a 1 ]
[ b 2 ] )
( display a )
( display b ) )
( define-syntax my-let*
( syntax-rules ()
[ ( my-let* ( [ var exp ] ) body ... )
( my-let ( [ var exp ] ) body ... ) ]
[ ( my-let* ( [ var exp ]
[ var1 exp1 ] ... ) body ... )
( my-let ( [ var exp ] )
( my-let* ( [ var1 exp1 ] ... )
body ... ) ) ] ) )
( define-syntax my-for
( syntax-rules ()
[ ( my-for ( var from to ) body ... )
( let loop ( [ var from ] )
( my-when
( < var to )
body ...
( loop ( + var 1 ) ) ) ) ] ) )
( my-for
( i 0 10 )
( display "a" )
( display "b" ) )
( syntax-rules ( begin end from to )
[ ( loop <var> from <min> to <max> start body ... end )
( let loop1 ( [ <var> <min> ] )
( cond
[ ( < <var> <max> ) body ... ( loop1 ( + 1 <var> ) ) ]
[ else ( void ) ] ) ) ] ) )
( loop i from 1 to 10
begin
( display 1 )
( newline )
( display 2 )
( newline )
end )
( define-syntax my-when
( syntax-rules ()
[ ( _ pred body ... )
( if pred ( begin body ... ) ( void ) ) ] ) )
( my-when
( = 2 1 )
( display 1 )
( display 2 ) )
( define-syntax my-let
( syntax-rules ()
[ ( my-let ( [ var exp ] ... )
body ... )
( ( lambda ( var ... )
body ... ) exp ... ) ] ) )
( my-let
( [ a 1 ]
[ b 2 ] )
( display a )
( display b ) )
( define-syntax my-let*
( syntax-rules ()
[ ( my-let* ( [ var exp ] ) body ... )
( my-let ( [ var exp ] ) body ... ) ]
[ ( my-let* ( [ var exp ]
[ var1 exp1 ] ... ) body ... )
( my-let ( [ var exp ] )
( my-let* ( [ var1 exp1 ] ... )
body ... ) ) ] ) )
( define-syntax my-for
( syntax-rules ()
[ ( my-for ( var from to ) body ... )
( let loop ( [ var from ] )
( my-when
( < var to )
body ...
( loop ( + var 1 ) ) ) ) ] ) )
( my-for
( i 0 10 )
( display "a" )
( display "b" ) )
;;; 一种比較有意思的使用方法
( define-syntax loop( syntax-rules ( begin end from to )
[ ( loop <var> from <min> to <max> start body ... end )
( let loop1 ( [ <var> <min> ] )
( cond
[ ( < <var> <max> ) body ... ( loop1 ( + 1 <var> ) ) ]
[ else ( void ) ] ) ) ] ) )
( loop i from 1 to 10
begin
( display 1 )
( newline )
( display 2 )
( newline )
end )
scheme 中的宏使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。