简体   繁体   中英

Get function as parameter in haskell

I can't figure this, I have a type called Enumeration

> type Enumeration a = Int -> [a]

And I need to map over it. I wrote this following function:

> imapE :: (a -> b) -> Enumeration a -> Enumeration b
> imapE f (m fa) = \n -> imapF f fa

where imapF is defined like this:

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

but when I try to load my code I get the following error BinaryTrees.lhs:91:14: Parse error in pattern: m regarding my imapE function.

I am trying to get the first enumeration Enumeration a as the function it is (Int and [a])

You cannot pattern match over a function, but you don't have to do that:

> imapE :: (a -> b) -> Enumeration a -> Enumeration b
> imapE f g = (imapF f) . g

(Well, imapF is just map really).

Without using . :

> imapE :: (a -> b) -> Enumeration a -> Enumeration b
> imapE f g = \n -> imapF f (g n)

A possible solution could be

imapE :: (a -> b) -> Enumeration a -> Enumeration b
imapE = map . map

Indeed, the above is equivalent to

imapE f = map (map f)

where

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

since both [] and (->) Int are functors.

The main "trick" to this kind of exercises is to think more about the types than the actual values.

This might feel a bit obscure if you're a beginner. Once you'll get more familiar with functors, however, this will become quite natural.

(People very accustomed to this style could even hint to this solution with some cryptic note "functors compose", and leaving you to figure out what's really going on. When that happens, don't give up -- eventually it will make sense ;-))

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