forA vs map
- Neelam_DwivediOP
I am trying to come up with examples on how forA and map work similarly with just their arguments switched. The following code is an attempt at that:
encryptListUsingMap : [Text] -> [Text] encryptListUsingMap x = map sha256 x encryptListUsingForA: [Text] -> [Text] encryptListUsingForA x = forA x sha256The
map sha256 xworks, butforA x sha256doesn’t compile. The error message isCouldn't match type ‘Text’ with ‘m b’ Expected type: Text -> m b Actual type: Text -> Text • In the second argument of ‘forA’, namely ‘sha256’ In the expression: forA x sha256Does it have something to do with the way sha256 works?
Just to add to this, the following two statements work fine:
forA x (%) y map (% y) x - Gary_Verhaegen
Hi @Neelam_Dwivedi,
forAis not “mapwith its arguments switched”. If you want “mapwith its arguments switched”, you can use(flip map).Let’s take a look at their types:
map : (a -> b) -> [a] -> [b] forA : (Applicative m) => [a] -> (a -> m b) -> m [b]As you can see, there’s this
Applicativeconstraint in the way. You can think offorAas the equivalent ofmapbut for actions.Here’s a concrete example:
module Main where import Daml.Script pretend_script : Int -> Script Int pretend_script x = return (x + 1) setup : Script () setup = script do let a : [Script Int] = map pretend_script [1, 2, 3] let b : Script [Int] = forA [1, 2, 3] pretend_script -- c <- a -- this line fails d <- b -- this succeeds e <- sequence a -- also succeeds return ()Notice the difference in types between
aandb. Specifically, you can “unwrap”bwith<-notation, but you can’t do the same fora(without using thesequencefunction).For completeness:
sequence : (Applicative m) => [m a] -> m [a] - Neelam_Dwivedi
Thanks @Gary_Verhaegen
Yes, the documentation also compares forA with mapA, and not with map and so my guess was also that this has something to do with forA taking Applicative f, while map takes (a ->b). But I got thrown off when I saw that forA takes (%).
Thanks for a great explanation!