Why is there no `for` in daml?
- meetOP 3
DAML seems to have a
forAcorresponding to amapA. Just for the sake of completeness, why is there noforcorresponding to amap? - cocreature 3
This is primarily due to being based on Haskell. Haskell has a
forfunction but it is actually equivalent toforAin DAML. So to avoid any potential confusion, we did not add aforto DAML. That said, I don’t think it would be that unreasonable to add it. - Andrae 2
Be aware that
mapis specialised to list, and as such we generally prefer to usefmapwhich is the same function generalised over allFunctor’s from whichmapis derived. This contrasts withmapAwhich is already generalised overApplicativeandTraversable*.Moreover when we use
fmap(over[],Optional,NonEmpty,Update, or some otherFunctor), we generally use the operator version<$>. So instead of writingfmap someFunction someListwe writesomefunction <$> someFunctor. This is generally easier to read, especially as operator precedence often allows us to eliminate multiple parentheses by using an operator like this**.There are occasions where the code is easier to read if we swap the function and the list arguments — fortunately, while there is no
forfunction in the standard library, there is aforoperator<&>. So you can always writesomeFunctor <&> someFunction.In short, you will almost always find your code easier to read and write if you use
<$>in preference tofmapand occasionally<&>where you want the arguments flipped.- In fact in much the same way the existence of a lawful
fmapis what defines aFunctor, the existence of a lawfulmapAis what defines aTraversable.
** The two common exceptions to this are:
- Where you want to partially apply
fmapto define a function. ie.
f : Update Text -> Update Int f = fmap length- Where you need to fmap over nested functors, ie. applying
f : (a -> b)toarg : [Optional a]to get[Optional b]. So we do find a few places in our code where we writefmap f <$> arg.
A quick grep indicates 1805 uses of
<$>, 241 uses of<&>, 267 uses offmap(the vast majority of which fall into case 1 above).PS. As an aside, as you move from introductory to intermediate DAML, it is highly recommended that you take the time to explore and understand the core typeclasses
Functor,Applicative,Action, andTraversable, their functions, operators, and hierarchy, as advanced DAML techniques often assume a familiarity with these concepts, and they do allow you to simplify otherwise quite complicated DAML code. - In fact in much the same way the existence of a lawful