2014-11-22 45 views
10

對於分配我的函數列表上的工作列表[Int -> Int](如:[(+3), (*4), (+1)]),我想一個Int適用於每個人,又將創造一個結果列表[Int]哈斯克爾申請單值函數

我已經搜索了很多,但我無法找到一種方法來做這樣的操作。使用map不能像我所期望的那樣工作。相關的錯誤是這樣的:

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) 

這種實際工作。文件中有一段錯誤的代碼仍然存在,對不起。

+1

告訴我們使用地圖的代碼 – 2014-11-22 18:03:05

+0

這與您的問題無關,但您的「樹」類型有點奇怪。我完全不知道你在做什麼,但它似乎融合了兩個概念:製作一個事物樹,並將某些事情組合在一起。你可能要考慮使用'Data.Tree'(來自GHC附帶的'containers'包),此時與你類型非常接近的東西可以表示爲'Tree(Label - > Label,Label)'。通過像這樣分解它,你可以使用各種通用的'Tree'函數。 – dfeuer 2014-11-22 18:19:05

+0

此樹型在作業中給出。大概是爲了讓學生們生生不息。 – nitowa 2014-11-22 18:27:04

回答

21

可以使用$運營商,它代表的功能應用。

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

這基本上擴展到[(+3) $ 3, (*4) $ 3, (+1) $ 3],這只是功能應用。

2

如果flist是函數列表,並且x是參數,則需要map (\f -> f x) flist

例如

Prelude> map (\f -> f 10) [(4 +), (3 *)] 
[14,30]