Sotiris Kal.
Sotiris Kal.

Reputation: 68

A simple version of Haskell's map

I'm trying to define map in ghci recursively. What I've come up with so far is the following:

let mymap f (x:xs) = if null xs then [] else f x : map f xs

What I'd like to do now is to simplify it a bit and hardcode the list inside the code, i.e., write a map function which takes a function as argument and does what the real map does but only to a specific list e.g., [1, 2, 3, 4, 5]. Is such a thing possible?

Upvotes: 1

Views: 4057

Answers (1)

bheklilr
bheklilr

Reputation: 54058

First of all, your map function isn't entirely correct. If I were to input mymap (+1) [1], I would expect to get [2] back, but instead I'd get []. If I tried mymap (+1) [], my program would crash on a pattern match failure, since you haven't defined that case. Instead, consider defining your mymap as

mymap :: (a -> b) -> [a] -> [b]
mymap f [] = []
mymap f (x:xs) = f x : mymap f xs

If you want to do it inline with an if statement then you'd have to do

mymap f xs = if null xs then [] else f (head xs) : mymap f (tail xs)

These do essentially the same thing, but the first is a bit easier to read in my opinion.


If you want to use mymap to define a function that maps only over a specific list, you could do so pretty easily as

mapOnMyList :: (Int -> b) -> [b]
mapOnMyList f = mymap f [1, 2, 3, 4, 5]

Or in point-free form

mapOnMyList = (`mymap` [1, 2, 3, 4, 5])

using mymap as an infix operator. This is equivalent to flip mymap [1, 2, 3, 4, 5], but the operator form is usually preferred since flip is not necessarily free to execute.


You can also do this using list comprehensions:

mymap f xs = [f x | x <- xs]

Or if you want to hard code the list

mapOnMyList f = [f x | x <- [1, 2, 3, 4, 5]]

Upvotes: 6

Related Questions