hakuna matata
hakuna matata

Reputation: 3327

custom map function standard ml

I want to make a custom map function that does the same thing as the predefined map function in sml, I wrote the following code:

fun mymap f = fn L => foldr f [] L;

Which is bascially a function f, that can then take a list and apply the function f to the list, since map function takes a list and function and return the another list, now what I'm getting is :

val mymap = fn : ('a * 'b list -> 'b list) -> 'a list -> 'b list

but the predefined map function has the following output:

val it = fn : ('a -> 'b) -> 'a list -> 'b list

what is the problem that I made here? Thanks

NOTE: I must use foldr or foldl function and use currying

Upvotes: 0

Views: 1289

Answers (2)

Alex
Alex

Reputation: 1177

Well, you must understand, that for each element of the list you apply foldr on, it takes an element of that list, the previous result (or the start-value) and gives both to the function wich is the first parameter of foldr.

That means, that in the code you wrote, f takes two parameters. So f takes a value of the list ('a) and a list ('b list), and that gives us the type:

'a * 'b list -> 'b list

But in the map function, you want f to be applied to each list element, so you need to make foldr's first argument an abstraction, wich applies f to the list elements, and adds the result to the output list.

Upvotes: 1

newacct
newacct

Reputation: 122449

What is the problem? Well, as you can see, the problem is that the first argument to your function (f) has the wrong type to be used as the first argument to foldr. You must first understand what kind of function is required as the first argument for foldr.

Upvotes: 1

Related Questions