【问题标题】:High order function thats has for input a list of functions and a list of elements and applies the functions to the elements具有用于输入的函数列表和元素列表并将函数应用于元素的高阶函数
【发布时间】:2017-03-28 10:26:53
【问题描述】:

正如标题所示,我正在尝试实现一个声明为的高阶函数

Ord u => [v->u]->[v]->[u]

具有输入 a) 任何类型的函数列表和任何类型的值范围和 b) 相同类型的元素列表,然后它将返回一个列表,该列表是所有发生的元素的结果从将给定列表中的函数应用到给定列表中的元素以升序排列,没有重复值。

我试图用 foldr 函数来实现它,但没有成功。 我认为我可以将 zip 函数作为一对索引,以便它们将与 foldr 函数一起应用。下面我创建了一个插入排序,因此我可以对最终列表进行排序

apply :: Ord u => [v->u]->[v]->[u]             
apply f y = insSort (foldr(\(i, x) y -> x:y ) (zip [1..] f))

insSort :: Ord u => [u] -> [u]
insSort (h:t) = insert h (insSort t)
insSort [] = []

insert :: Ord u => u -> [u] -> [u]
insert n (h:t)
            | n <= h = n : h : t
            | otherwise = h : insert n t
insert n [] = [n]

例如一些输入和输出:

>apply [abs] [-1]
[1]

>apply [(^2)] [1..5]
[1,4,9,16,25]

>apply [(^0),(0^),(\x->div x x),(\x->mod x x)] [1..1000]
[0,1]

>apply [head.tail,last.init] ["abc","aaaa","cbbc","cbbca"]
"abc"

> apply [(^2),(^3),(^4),(2^)] [10]
[100,1000,1024,10000]

>apply [(*5)] (apply [(‘div‘5)] [1..100])
[0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]

【问题讨论】:

  • 你能展示你对 foldr 的尝试吗? :)
  • @user54264611634646244 当然,我只是编辑了它

标签: haskell


【解决方案1】:
apply :: [a -> b] -> [a] -> [b]

首先,此签名与标准&lt;*&gt; 函数的签名相匹配,该函数是Applicative 类的一部分。

class Applicative f where
    pure :: a -> f a
    (<*>) :: f (a -> b) -> f a -> f b

设置f ~ [] 我们有&lt;*&gt; :: [a -&gt; b] -&gt; [a] -&gt; [b]

至少有两种合理的方法可以为列表编写Applicative 实例。第一个采用其输入的笛卡尔积,将每个函数与每个值配对。如果&lt;*&gt; 的输入列表的长度为 NM,则输出列表的长度为 N*M。该规范的pure 会将一个元素放入单例列表中,因此pure id &lt;*&gt; xs = xs

instance Applicative [] where
    pure x = [x]
    (f:fs) <*> xs = map f xs ++ (fs <*> xs)

这相当于the standard Applicative instance for []

实现Applicative 的另一种明智的方法是将两个列表压缩在一起,方法是将函数逐点应用于元素。如果&lt;*&gt; 的输入列表的长度为NM,则输出列表的长度为min(N, M)pure 创建了一个无限列表,所以再次pure id &lt;*&gt; xs = xs

instance Applicative [] where
    pure x = let xs = x:xs in xs
    [] <*> _ = []
    _ <*> [] = []
    (f:fs) <*> (x:xs) = f x : (fs <*> xs)

此实例在base 下的the ZipList newtype 中可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 2014-09-24
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多