Mateusz Piotrowski
Mateusz Piotrowski

Reputation: 9127

Difficulties with applying a function to a list of lists using mapping

I am trying to use my own map function to map a function f to a list of lists L. The problem is that the program doesn't run. I guess I've made some kind of a syntax error. Nevertheless, it might be something connected to the misuse of cond or even misunderstanding of the idea of mapping a list of lists.

I am not experienced in functional programming and the Scehme language and that's why I cannot solve it on my own. I've tried different ways of conditioning and searched through the StackOverflow for similar questions however I could find any solution.

Here is my code. I've added some comments to show you the way I think about this functions.

(define (mapp f L)
    (cond
        [(null? L) '()] ; if L is empty
        [(list? (car L)) ; if the head of L is a list
            (cons
                (mapp f (car L))  ; do mapp for the head of L which is a list
                (mapp f (cdr L))  ; do mapp for the tail of L
        )]
        [else (cons
                (f (car L)) ; do f for the head which is a number
                (mapp f (cdr L)) ; do mapp for the tail of L
        )]
    )
)


(define (fun a)
    (expt a 2)) ; I chose expt function just to see if something changes

(display
    (mapp fun (1 2 3 (4 3 2) 6 (0 2) 9) ) 

;I expect the output to be (1 4 9 (16 9 4) 36 (0 4) 81)

Upvotes: 1

Views: 56

Answers (1)

Óscar López
Óscar López

Reputation: 236014

The procedure is fine, as mentioned in the comments there's a problem with the sample input. Try this:

(mapp fun '(1 2 3 (4 3 2) 6 (0 2) 9))
=> '(1 4 9 (16 9 4) 36 (0 4) 81)

You forgot the ' (a quote) at the beginning of the list! Also, we can do a small (but implementation-dependent) optimization: in your code replace list? with pair?, in some interpreters pair? will be more efficient than list?.

Upvotes: 3

Related Questions