Get function as parameter in haskell

我的未来我决定 提交于 2020-01-06 23:00:10

问题


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])


回答1:


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)



回答2:


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 ;-))



来源:https://stackoverflow.com/questions/35688404/get-function-as-parameter-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!