Haskell将单个值应用于函数列表 [英] Haskell apply single value to a list of functions

查看:80
本文介绍了Haskell将单个值应用于函数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个分配,我正在处理函数[Int -> Int]的列表(例如[(+3), (*4), (+1)]),我想对每个函数应用一个Int,从而创建结果列表[Int]

For an assignment I am working on a list of functions [Int -> Int] (eg. [(+3), (*4), (+1)] ) and I would like to apply a single Int to each of them, in turn creating a list of results [Int]

我已经进行了很多搜索,但是我无法找到执行此操作的方法.正如我所期望的那样,使用map无法正常工作.相关的错误是这样的:

I already searched a lot, but I am unable to find a way to do such an operation. Using map does not work as I would expect. The related error is this:

ERROR - Cannot infer instance
*** Instance   : Num ((Label -> Label) -> a)

根据要求输入代码:

data Tree = Node (Label -> Label) Label [Tree]
type Label = Int

testTree = Node (+1) 3 [ Node (+1) 5 [], Node (+1) 4 [Node (+1) 1 [], Node (+2) 7 []]]

listify :: Tree -> [(Label -> Label)]
listify t = [(getNodeFunction t)] ++ concat(map (listify) (getSubTrees t))


*Main> map (\f -> f 7) (listify testTree)

这实际上有效.文件中仍有一段错误的代码,为您大惊小怪.

this actually works. Had a piece of faulty code in the file still, sorry for the fuss.

推荐答案

您可以使用$运算符,表示函数应用程序.

You can use the $ operator, which stands for function application.

> map ($ 3) [(+3), (*4), (+1)]
[6,12,4]

这基本上扩展为[(+3) $ 3, (*4) $ 3, (+1) $ 3],它只是函数应用程序.

This basically expands to [(+3) $ 3, (*4) $ 3, (+1) $ 3], which is just function application.

这篇关于Haskell将单个值应用于函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆