Racket[0]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DanielDingshengli/article/details/81987279

记录生僻知识点

1.函数副作用
当调用函数时,被调用函数除了返回函数值之外,还对主调用函数产生附加的影响。
良性副作用:通过指针或引用参数设计的函数,都具有访问外部数据的倾向。或许可以利用某个函数对外部数据的修改,简化或免于后续计算的工作。
恶性副作用:内存泄漏是一种典型的函数恶性副作用。
2.散列表

;; 创建一个不变的散列表 (可变散列表的例子在下面)
(define m (hash 'a 1 'b 2 'c 3))
;; 根据键取得值
(hash-ref m 'a) ; => 1
;; 获取一个不存在的键是一个异常
; (hash-ref m 'd) => 没有找到元素
;; 你可以给不存在的键提供一个默认值
(hash-ref m 'd 0) ; => 0
;; 使用 `hash-set' 来扩展一个不可变的散列表
;; (返回的是扩展后的散列表而不是修改它)
(define m2 (hash-set m 'd 4))
m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3))
;; 记住,使用 `hash` 创建的散列表是不可变的
m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d'
;; 使用 `hash-remove' 移除一个键值对 (函数式特性,m 并不变)
(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)

3.将函数赋值给一个变量
这里写图片描述

;; 你也可以使用可变参数, `case-lambda'
(define hello3
 (case-lambda
 [() "Hello World"]
 [(name) (string-append "Hello " name)]))
(hello3 "Jake") ; => "Hello Jake"
(hello3) ; => "Hello World"
;; ... 或者给参数指定一个可选的默认值
(define (hello4 [name "World"])
 (string-append "Hello " name))

4.使用关键字

(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args)
 (format "~a ~a, ~a extra args" g name (length args)))
(hello-k) ; => "Hello World, 0 extra args"
(hello-k 1 2 3) ; => "Hello World, 3 extra args"
(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args"
(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args"
(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6)
 ; => "Hi Finn, 6 extra args"

5.模式匹配

> (define (hello? n)
    (match(list(remainder n 3)(remainder n 5))
      [(list 0 0) 'oo]
      [(list _ 0) '_o]
      [(list 0 _) 'o_]
      [_ #f]))
> (hello? 15)
'oo
> (hello? 10)
'_o
> (hello? 37)
#f
> 

6.迭代

(for ([i (in-list '(l i s t))])
 (displayln i))
(for ([i (in-vector #(v e c t o r))])
 (displayln i))
(for ([i (in-string "string")])
 (displayln i))
(for ([i (in-set (set 'x 'y 'z))])
 (displayln i))
(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))])
 (printf "key:~a value:~a\n" k v))
> (for ([i 10][j '(x y x)])
    (printf "~a:~a\n" i j))
0:x
1:y
2:x
(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10))
 i) ; => '(6 8 10)

7.模块

;; 模块让你将你的代码组织为多个文件,成为可重用的模块
(module cake racket/base ; 基于 racket/base 定义一个 `cake` 模块
 (provide print-cake) ; 这个模块导出的函数
 (define (print-cake n)
 (show " ~a " n #\.)
 (show " .-~a-. " n #\|)
 (show " | ~a | " n #\space)
 (show "---~a---" n #\-))
 (define (show fmt n ch) ; 内部函数
 (printf fmt (make-string n ch))
 (newline)))
 //require后运行注意会报错

8.宏
这里写图片描述
9.bracket

在Racket里,小括号和方括号本质上意义一样。用方括号只是一种约定俗成的使用,主要是为了增加程序的可读性。
方括号一般用在以下几个方面:
1、let:
(let ([id expr] ...) body ...+)
2、cond:
(cond [test-expr body ...+]
      ...)
3、case:
(case expr
  [(datum ...+) body ...+]
  ...)
4、contract:
(provide (contract-out [amount positive?]))

猜你喜欢

转载自blog.csdn.net/DanielDingshengli/article/details/81987279
0