简体   繁体   中英

How to use 'let' and 'map' to simplify a recursive function in racket?

I'm stuck on a practice problem that requires me to simplify a recursive function by using 'let' and 'map'.

The original function (biggest-number) takes a list as input and outputs the biggest number in that list. (ex: (biggest-number (list 1 2 3)) -> 3 Here's the code for the original function.

(define (biggest-number list1)
  (cond
    [(empty? (rest list1)) (first list1)]
    [(cons? (rest list1))
     (if (> (first list1) (biggest-number (rest list1)))
         (first list1)
         (biggest-number (rest list1)))]))

I'm just having trouble finding a lambda function to use map with. This is what I have so far, which is very wrong and worsened the original.

(define (simple-max list1)
  (cond
    [(empty? (rest list1)) (first list1)]
    [(cons?  (rest list1))
    (let ((test (lambda (number) (if (> number (simple-max (rest list1)))
                                number
                                (simple-max (rest list1))))))
      (map test list1))]))

I want to start by finding a lambda function that can replace the 'if' statement, and then use 'let' to assign a variable to the lambda equation. Can someone help me with the thinking process to get the lambda function?

I don't know how you would use map to simplify a catamorphic function (ie a function which folds a data structure into a value). In your case, you are folding a list into the biggest number of that list:

biggest-number :: [Int] -> Int

You can't use map because map is a structure preserving operation:

map :: (a -> b) -> [a] -> [b]

You need to fold the list into a value using an operation such as foldl :

foldl :: (b -> a -> b) -> b -> [a] -> b

This is how I would write it:

(define (max x y) (if (> x y) x y))

(define (biggest-number list) (foldl max (car list) (cdr list)))

Simple and succinct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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