racket/scheme filtering

2019-07-15 08:07发布

问题:

How would I filter this to display all vegetables? Thank you in advance.

("Pecan" . (1982 .("nut". "AL")))

("Blackberry" . (2004 .("fruit". "AL")))

("Peach" . (2006 .("fruit". "AL")))

("Rice" . (2007 .("grain". "AR")))

("Orange" . (2005 .("fruit". "FL")))

("Huckleberry" . (2000 .("fruit". "ID")))

("Blackberry" . (2004 .("fruit". "KY")))

("Strawberry" . (1980 .("fruit". "LA")))

("WildBlueberry" . (1991 .("fruit". "ME")))

("BlueCrab" . (2000 .("food". "MD")))

("HoneycrispApple" . (2006 .("fruit". "MN")))

("Pumpkin" . (2000 .("fruit". "NH")))

("Chile" . (1965 .("vegetable". "NM")))

("Blueberry" . (2001 .("fruit". "NC")))

("ChokeCherry" . (2007 .("fruit". "ND")))

("WaterMelon" . (2007 .("vegetable". "OK")))

("Pear" . (2000 .("fruit". "OR")))

("Hazelnut" . (2000 .("nut". "OR")))

("Peach" . (1984 .("fruit". "SC")))

("Tomato" . (2003 .("fruit". "TN")))

("Jalapeno" . (1995 .("vegetable". "TX")))

("Apple" . (2000 .("fruit". "WA")))

回答1:

Pack all of the elements in a single list (called lst in the code below) and run this filter on it:

(filter (lambda (x) (string=? "vegetable" (caddr x)))
        lst)

=> '(("Chile" 1965 "vegetable" . "NM")
     ("WaterMelon" 2007 "vegetable" . "OK")
     ("Jalapeno" 1995 "vegetable" . "TX"))