I'm new to scheme and working on a problem defined as follows:
Write a function named longer-list that takes two list arguments and returns the longer list of the two inputs. If the two lists are equal in length, the function returns #t, and if one of the arguments is not a list, the function should return #f. Note: You are not allowed to use the predefined length function; however, you can write your version of length or other helper functions that you may want to call from longer-list.
Sample runs:
(longer-list '(1 2 3 4) '(a b c d e)) returns (a b c d e)
(longer-list '(d e f) '(4 5 6)) returns #t (or true)
(longer-list '(g h i) 3) returns #f (or false)
what I have so far is:
;;helper function to determine the length of a list
(define (list-length lst)
(if (null? length)
0
(+1 (list-length (cdr lst)))))
;;main function to return the longer of 2 lists or True if they are equal
(define (longer-list lst1 lst2)
;;check if both parameters are actually lists
(and (list? lst1)
(list? lst2)
;;if lst1 is the longer list return lst1
(if(> (list-length lst1) (list-length lst2))
lst1)
;;else lst2 is longer, return that
(else (> (list-length lst1 (list-length lst2))
lst2))
;define comp as comparing list1 abbreviated by x and list2 abbreviated by y???
(let comp ((x lst1) (y lst2))
(cond
;;if both lists are null return true
((and (null? x) (null? y)) #t)
;;not sure what this means?
((null? x) lst2)
;;not sure what this means?
((null? y) lst1)
;;else invoke comp after the first element of each list is removed???
(else (comp (cdr x) (cdr y)))))))
Currently I'm getting the following error:
"if: missing an "else" expression in: (if (> (list-length lst1) (list-length lst2)) lst1)"
My question is what is causing this error. Additionally, I found some of this code online and need to make sure I fully understand it so if someone could check my comments to see if they make sense, it would be greatly appreciated.
Aucun commentaire:
Enregistrer un commentaire