Reputation:
I am given two lists in scheme and check whether we can form the one of them from the elements of the other. In other words, i check whether this is an . To do this, i implemented a function called member?, which takes a symbol and a list, and if this symbol is in the list then this function removes that symbol from the list and returns the new list. The sample input-output for the function is like the following:
I am thinking about doing the following: Since we have two lists to check the , i take the first list and for each symbol in that list, by using member? function, i check whether that symbol occurs in the other list. Finally at the end, if it is an then we have an empty list. Here is some trials to do this:
(define member?
(lambda (inSym inSeq)
(if (and (symbol? inSym) (sequence? inSeq)) ; can remove?
(remove-member inSym inSeq) ; then remove!
'can-not-remove))) ; otherwise, present an error message
(define
(lambda (inSeq1 inSeq2)
(if (and (sequence? inSeq1) (sequence? inSeq2)) ;if both are sequences
(if(equal? '() (member? (car inSeq1) inSeq2))) ... ???
)
)
I could not organize the recursion needed here. Can anyone help me with this?
Thank you.
Upvotes: 1
Views: 107
Reputation: 235984
Just for the record: the simplest way to check if two sequences are anagrams is to sort them and see if they're equal:
(define symbol<?
(lambda (s1 s2) ; compare two symbols
(string<? (symbol->string s1)
(symbol->string s2))))
(define anagram?
(lambda (inSeq1 inSeq2)
(and (sequence? inSeq1) ; a sequence is a list of symbols
(sequence? inSeq2) ; a sequence is a list of symbols
(equal? (sort inSeq1 symbol<?) (sort inSeq2 symbol<?)))))
Upvotes: 2
Reputation: 1339
Using sort is not efficient and for your implementation You do not need the member? function:
(define remove-member
(lambda (n lst)
(cond ((null? lst)
'())
((equal? (car lst) n)
(cdr lst))
(else
(cons (car lst)
(remove-member n (cdr lst)))))))
(define anagram?
(lambda (lst1 lst2)
(cond ((and (null? lst1) (null? lst2))
#t)
((or (null? lst1) (null? lst2))
#f)
(else
(anagram? (cdr lst1) (remove-member (car lst1) lst2))
))))
Upvotes: 2
Reputation: 12670
(define canFind?
(lambda (item sequence)
(if (null? sequence)
#f
(if (equal? item (car sequence))
#t
(canFind? item (cdr sequence))
)
)
)
)
(define remove
(lambda (item sequence)
(if (equal? item (car sequence))
(cdr sequence)
(append (list (car sequence)) (remove item (cdr sequence)))
)
)
)
(define isAnagram?
(lambda (seq1 seq2)
(if (and (null? seq1) (null? seq2))
#t
(if (or (null? seq1) (null? seq2))
#f
(if (canFind? (car seq1) seq2)
(isAnagram? (cdr seq1) (remove (car seq1) seq2))
#f
)
)
)
)
)
Upvotes: -1