Skip to content

Commit 6004e00

Browse files
author
pimgeek
committed
Update sort_chared.md
提供一个 racket 5.2.1 的解法
1 parent 84ae487 commit 6004e00

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

‎sort_chared.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,38 @@
4040
print "\nthe result is:"
4141
print sort_by_list(by_string,word)
4242

43+
# 解法 (racket 5.2.1)
4344

45+
**对语言的掌握还不熟练,所以暂未考虑算法效率**
46+
47+
```racket
48+
#lang racket
49+
50+
; 定义一个函数 filter-by-1st-char
51+
; 输入一个字符 a-ch 和一个字符串 a-str
52+
; 如果 a-ch 与 a-str 的第一个字符相同,
53+
; 则以列表方式输出 a-str, 否则输出空列表 '()
54+
(define (filter-by-1st-char a-ch a-str)
55+
(if (char=? a-ch (string-ref a-str 0))
56+
(list a-word) '()))
57+
58+
; 定义一个函数 sort-words-by-char-list
59+
; 它接受以字符串形式输入的一个字符序列 char-list,
60+
; 和以字符串列表形式输入的一个字符串序列 word-list
61+
; 输出一个列表,其所有列表项即 word-list 中的所有字符串
62+
; 并且将根据每个字符串的首字母,依照 char-list 所提供的顺序排序
63+
; 而并非按一般英文词典的 a-z 顺序排序
64+
(define (sort-words-by-char-list char-list word-list)
65+
(let
66+
([sorted-word-list '()]) ; 定义一个空列表用于存储排序后的 word
67+
(for ([ch char-list])
68+
(for ([wd word-list])
69+
(set! sorted-word-list
70+
(append sorted-word-list ; 把符合条件的单词放进结果列表
71+
(filter-by-1st-char ch wd)))))
72+
sorted-word-list))
73+
74+
; 函数调用,正常运行时,应该输出 (dear dog eye bed)
75+
(displayln
76+
(sort-words-by-char-list "dgecfboa" '("dear" "dog" "eye" "bed")))
77+
```

0 commit comments

Comments
 (0)