繁体   English   中英

球拍/方案返回列表连接的第一个列表

[英]Racket/Scheme Return the first list of a connection of lists

我有以下表达:

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

我敢肯定,必须有一个更简单的解决方案,它返回更有用的列表。 我是该语言的新手,我将不胜感激。

您有两个选择来获取列表'(* * *)

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

看一下正确的和正确的
(定义第一个'(* * *(---(* * *))))

(drop-right lst 1) will return '(* * *)  
(take-right lst 1) will return '((- - - (* * *)))

关于您编辑的问题:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM