我有以下表达式:
(list '* '* '* (list '- '- '- (list '* '* '*)))
我想提取:
(list '* '* '*)
(first (list '* '* '* (list '- '- '- (list '* '* '*))))
因某些原因无效。你们有什么想法如何解决这个问题?
编辑:好的,谢谢!现在我遇到了问题。
所以我的主要问题是产生一个如下所示的列表:
(define a '((* * *) (- - -) (* * *)))
我试图将莫尔斯代码分成几个代表字母的部分。每个字母都用间隙符号分隔。我现在的功能如下:
(define (break-sign los sign)
(cond
[(empty? (rest los)) (cons (first los) empty)]
[(symbol=? (first (rest los)) sign) (cons (first los) (cons (break-sign (rest (rest los)) sign) empty))]
[else (cons (first los) (break-sign (rest los) sign))]
)
)
它产生一个这样的列表,很难分开:
(list '* '* '* (list '- '- '- (list '* '* '*)))
我确信必须有一个更简单的解决方案,它会返回一个更有用的列表。我对这门语言不熟悉,我将不胜感激。
答案 0 :(得分:0)
您可以通过两种方式获取列表'(* * *)
:
> (define a '(* * * (- - - (* * *))))
> (fourth (fourth a))
'(* * *)
> (take a 3)
'(* * *)
有什么区别?请考虑这一点(与列表相同的结构,但内容不同):
> (define a '(1 2 3 (4 5 6 (7 8 9))))
> (fourth (fourth a))
'(7 8 9)
> (take a 3)
'(1 2 3)
如果您希望first
方法有效,那么输入必须看起来像这样:
> (define a '((* * *) (- - -) (* * *)))
> (first a)
'(* * *)
> (third a)
'(* * *)
答案 1 :(得分:0)
看右下方和右下方 (定义lst'(* * *( - - - (* * *))))
(drop-right lst 1) will return '(* * *)
(take-right lst 1) will return '((- - - (* * *)))
答案 2 :(得分:0)
关于您编辑过的问题:
(define (break lst)
; I'm defining a helper function here
; and it's going to do all the work.
; It needs one more parameter than break,
; and break has special logic for the fully empty list.
(define (go lst group-so-far)
(cond [(empty? lst)
; Then this is the last group
; and we return a list containing the group
(cons group-so-far '())]
[(symbol=? (first lst) (first group-so-far))
; We extend the group with the element
; And recurse on the rest of the list
(go (rest lst)
(cons (first lst) group-so-far))]
[else
; We know that lst isn't empty
; But the sign changes, so we cons the group we have on
; the front of the list of groups we get when we
; run the function on the rest of the input.
; We also start it by passing the next element in
; as a group of size 1
(cons group-so-far
(go (rest lst)
(cons (first lst) '())))]))
; The empty list is special, we can't start the recursion
; off, since we need an element to form a group-so-far
(if (empty? lst)
'()
(go
(rest lst)
(cons (first lst) '()))))