1

我有以下表达式:

(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 '* '* '*)))

我确信必须有一个更简单的解决方案,它会返回一个更有用的列表。不过,我是这门语言的新手,如果有任何帮助,我将不胜感激。

4

3 回答 3

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) '()))))
于 2013-05-21T13:54:55.783 回答
0

查看 drop-right 和 take-right
(define lst '(* * * (- - - (* * *))))

(drop-right lst 1) will return '(* * *)  
(take-right lst 1) will return '((- - - (* * *)))
于 2012-11-18T07:46:59.457 回答
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)
'(* * *)
于 2012-11-11T02:19:01.410 回答