2012-11-10 71 views
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 '* '* '*))) 

我敢肯定,必須有一個更簡單的解決方案,它返回一個更有用名單。我是新來的語言,但我會很感激任何幫助。

+0

你是說,而不是'(名單 '*' * '*(名單' - ' - ' - (名單 '*' *「*))) '你想要'(list(list'*'*'*)(list' - ' - ' - )(list'*'*'*))'? –

+0

你還可以爲'break-sign'顯示一些示例輸入嗎?我不知道該功能正在嘗試做什麼。 –

回答

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

好吧,現在我得到線索:) – user1814735

+0

但是,我仍然無法創建一個函數,它提供了我需要的「第一個」方法的工作列表。我編輯了這篇文章以提供更多信息。 – user1814735

0

看滴右走右
(LST定義「(* * *( - - - (* * *))))

(drop-right lst 1) will return '(* * *) 
(take-right lst 1) will return '((- - - (* * *))) 
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) '()))))