简体   繁体   English

在haskell中获取函数作为参数

[英]Get function as parameter in haskell

I can't figure this, I have a type called Enumeration 我不知道这个,我有一个叫做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的定义如下:

> 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. 但是,当我尝试加载代码时,出现以下错误BinaryTrees.lhs:91:14: Parse error in pattern: m关于我的imapE函数的BinaryTrees.lhs:91:14: Parse error in pattern: m

I am trying to get the first enumeration Enumeration a as the function it is (Int and [a]) 我正在尝试获取第一个枚举Enumeration a作为它的函数(Int和[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). (好吧, imapF实际上只是map )。

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. 因为[](->) Int都是函子。

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 ;-)) (非常习惯这种风格的人甚至可以用一些模糊的注解“ functors compose”来暗示这种解决方案,让您自己弄清楚到底是怎么回事。当发生这种情况时,请不要放弃-最终它将变得有意义; -))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM