Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell apply single value to a list of functions

Tags:

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]

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)

As requested the code:

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.

like image 635
nitowa Avatar asked Nov 22 '14 17:11

nitowa


1 Answers

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

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

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

like image 53
Jakub Arnold Avatar answered Sep 17 '22 13:09

Jakub Arnold