Exercising multiple updates within DAML choice - daml

Is it possible in DAML to use a map-like function to iterate over of list of contractids, retrieve them and execute a choice on each? This appears to be limited in DAML by the way everything needs to be wrapped in a single Update when executing a choice.
Here's an example of what I've attempted (noting the issues):
exerciseChoice: ContractId ContractB -> Update (ContractId ContractB)
exerciseChoice contractB = do (exercise contractB UpdateB with newText = "test")
template ContractA
with
party : Party
contracts: [ContractId ContractB]
where
signatory party
controller party can
nonconsuming UpdateA : [Update (ContractId ContractB)]
with newText : Text
do
-- a <- create ContractB with party = party; text = newText
-- a2 <- exerciseChoice a
-- return [a2] #these lines work fine
return map exerciseChoice contracts
-- #this doesn't work due to DAML implicitly adding Update before return definition
-- i.e. DAML expects type 'Update [Update (ContractId ContractB)]' based on this signature
-- we need a function which converts something like:
-- '[Update (ContractId ContractB)] -> Update [ContractId ContractB]'
template ContractB
with
party : Party
text: Text
where
signatory party
controller party can
UpdateB: ContractId ContractB
with newText: Text
do create this with text = newText
If this can be solved, can you also explain why when returning multiple tuples in DAML they seem to implicitly cast from (Update (ContractId A), Update (ContractId B)) to Update (ContractId A, ContractId B)?

The function map has type (a -> b) -> [a] -> [b] so map exerciseChoice contracts will have type [Update (ContractId ContractB)]. Turning a list of actions into a single action is conceptually simple. The resulting action is the action of performing each action in the list in sequence. And indeed, there is a function for that: sequence : (Applicative m) => [m a] -> m [a]. Update is an applicative so you could write sequence (map exerciseChoice contracts). However, this is such a common task that there is a specialised function mapA : (Applicative m) => (a -> m b) -> [a] -> m [b].
mapA exerciseChoice contracts should do the trick.

Related

How do I execute some code in DAML N times?

Say I have a choice that takes an integer that represents a count and I want to create a contract that number of times, i.e. execute some block of code that many times.
In Ruby for example this might look like this:
n.times do
#run some code here
end
How do I achieve this in DAML?
TLDR
To apply a ledger operation N times the easiest way is to use the replicateA function from DA.Action.
Example
daml 1.2
module ReplicateDaml
where
import DA.Action
template Demo
with
sig: Party
total: Int
where
signatory sig
testReplicate = scenario do
p <- getParty "party"
let
total = 10
p `submit` replicateA total $ create Demo with sig=p; total
Discussion
The type signature for replicateA is:
-- | `replicateA n act` performs the action n times, gathering the results.
replicateA : (Applicative m) => Int -> m a -> m [a]
You can read this as:
This function supports any type m that has an instance (implementation) for the Applicative typeclass (api or interface).
Its first parameter is an Int
Its second is an 'effect' of the type m that provides a value of type a
It returns the result of repeating the effect N times, collecting the results in a list
The create you describe is of type: Update (ContractId a); and as Update instantiates (has an implementation for) the Applicative typeclass you can use any function that works on Applicative's on Update's — which naturally includes replicateA.
When used this way, substitute Update for m and (ContractId t) for a in the type signature, so:
replicateA : Int -> Update (ContractId t) -> Update [ContractId t]

How to serialize function type to json in haskell?

data Task = Task
{ id :: String
, description :: String
, dependsOn :: [String]
, dependentTasks :: [String]
} deriving (Eq, Show, Generic, ToJSON, FromJSON)
type Storage = Map String Task
s :: Storage
s = empty
addTask :: Task -> Storage -> Storage
addTask (Task id desc dep dept) = insert id (Task id desc dep dept)
removeTask :: String -> Storage -> Storage
removeTask tid = delete tid
changes = [addTask (Task "1" "Description" [] []), removeTask "1"]
main = putStrLn . show $ foldl (\s c -> c s) s changes
Suppose I have the following code. I want to store changes list in a json file. But I don't know how to do that with Aeson, aside probably from writing a custom parser and there must be a better way to do that obviously. Like maybe using language extension to derive (Generic, ToJSON, FromJSON) for addTask and removeTask etc...
EDIT. For all people that say "You can't serialize function".
Read the comments to an answer to this question.
Instance Show for function
That said, it's not possible to define Show to actually give you more
? detail about the function. – Louis Wasserman May 12 '12 at 14:51
Sure it is. It can show the type (given via Typeable); or it can show some of the inputs and outputs (as is done in QuickCheck).
EDIT2. Okay, I got that I can't have function name in serialization. But can this be done via template Haskell? I see that aeson supports serialization via template Haskell, but as newcomer to Haskell can't figure out how to do that.
Reading between the lines a bit, a recurring question here is, "Why can't I serialize a function (easily)?" The answer -- which several people have mentioned, but not explained clearly -- is that Haskell is dedicated to referential transparency. Referential transparency says that you can replace a definition with its defined value (and vice versa) without changing the meaning of the program.
So now, let's suppose we had a hypothetical serializeFunction, which in the presence of this code:
foo x y = x + y + 3
Would have this behavior:
> serializeFunction (foo 5)
"foo 5"
I guess you wouldn't object too strenuously if I also claimed that in the presence of
bar x y = x + y + 3
we would "want" this behavior:
> serializeFunction (bar 5)
"bar 5"
And now we have a problem, because by referential transparency
serializeFunction (foo 5)
= { definition of foo }
serializeFunction (\y -> 5 + y + 3)
= { definition of bar }
serializeFunction (bar 5)
but "foo 5" does not equal "bar 5".
The obvious followup question is: why do we demand referential transparency? There are at least two good reasons: first, it allows equational reasoning like above, hence eases the burden of refactoring; and second, it reduces the amount of runtime information that's needed, hence improving performance.
Of course, if you can come up with a representation of functions that respects referential transparency, that poses no problems. Here are some ideas in that direction:
printing the type of the function
instance (Typeable a, Typeable b) => Show (a -> b) where
show = show . typeOf
-- can only write a Read instance for trivial functions
printing the input-output behavior of the function (which can also be read back in)
creating a data type that combines a function with its name, and then printing that name
data Named a = Named String a
instance Show (Named a) where
show (Named n _) = n
-- perhaps you could write an instance Read (Map String a -> Named a)
(and see also cloud haskell for a more complete working of this idea)
constructing an algebraic data type that can represent all the expressions you care about but contains only basic types that already have a Show instance and serializing that (e.g. as described in the other answer)
But printing a bare function's name is in conflict with referential transparency.
Make a data type for your functions and an evaluation function:
data TaskFunction = AddTask Task | RemoveTask String
deriving (Eq, Show, Generic, ToJSON, FromJSON)
eval :: TaskFunction -> Storage -> Storage
eval (AddTask t) = addTask t
eval (RemoveTask t) = removeTask t
changes = [AddTask (Task "1" "Description" [] []), RemoveTask "1"]
main = putStrLn . show $ foldl (\s c -> c s) s (eval <$> changes)

Using Dict.update with nested update functions in Elm

I'm writing an Elm app where a major part of the state is in a Dict with Records as values. I have an update function for the main state model, and an update function for the individual records in the Dict. Is there a way to use Dict.update with the record state update function?
The issue I'm having is that the state update function for the records returns what update functions usually return: a tuple with the updated object and any commands to trigger (e.g. (newRecord, Cmd.none)). But the Dict.update function needs to take in a record and return a record (e.g. just newRecord), not a tuple with a record and a command object.
Is there a way around this? Right now I've got it working using a combination of Dict.get and Dict.insert, but this seems clumsy.
If update function for record always return Cmd.none, you can simplify it and return only the updated model.
Child modules do not have to follow ( Model, Cmd Msg ) convention if your application architecture does not require that.
If you do need to pass Commands from the lower level, it is also possible to re-structure your child module's update function to simplify those updates.
Example based on example/http
Here is an example of how you can split the update so that you could re-use the same logic in the top-level update without additional trickery.
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
(updateModel msg model, updateCmd msg model)
updateCmd: Msg -> Model -> Cmd Msg
updateCmd msg model =
case msg of
MorePlease ->
getRandomGif model.topic
_ ->
Cmd.none
updateModel: Msg -> Model -> Model
updateModel msg model =
case msg of
NewGif (Ok newUrl) ->
Model model.topic newUrl
_ ->
model
If you need the updated model in updateCmd, then just pass it instead of current model or even pass both if you desire.
As a bonus, you can entirely omit unused branches of the case expression.
Using Dict.update
It will also be possible to use updateModel in Dict.update without retrieving the record and writing it back.
Dict.update childKey (Maybe.map (updateModel childMsg)) model
Not sure if this is what you are looking for, but if you have a nested Dict structure in your model, like this:
type alias Model =
{ parentsAndChildren : Dict String (Dict String Int) }
Then it is not necessary to make the child update output a Cmd. Your update could look something like this:
update : Msg -> Model -> Model
update msg model =
case msg of
NewChild parentName childName age ->
let
newModel =
{ model
| parentsAndChildren =
model.parentsAndChildren
|> Dict.update
parentName
(Maybe.map insertChild)
}
in
(newModel, Cmd.none)
-- helper function to update a child Dict
insertChild: String -> Int -> Dict (String Int) -> Dict (String Int)
insertChild name age childDict =
Dict.insert name age childDict
The only update function that NEEDS to output a Cmd is the update function in your top component.
So your child update function doesn't have to output a Cmd.
Not that I know of. I have this helper function in my one of my projects
updateDict : comparable -> msg -> Dict comparable b -> (msg -> b -> ( b, Cmd msg )) -> (comparable -> msg -> c) -> ( Dict comparable b, Cmd c )
updateDict uid act dict fn wrapper =
case Dict.get uid dict |> Maybe.map (fn act) of
Just ( m, e ) ->
( Dict.insert uid m dict
, Cmd.map (wrapper uid) e
)
Nothing ->
( dict, Cmd.none )

PolyML Functions and Types

[...] a pair of functions tofun : int -> ('a -> 'a) and fromfun : ('a -> 'a) ->
int such that (fromfun o tofun) n evaluates to n for every n : int.
Anyone able to explain to me what this is actually asking for? I'm looking for more of an explanation of that than an actual solution to this.
What this is asking for is:
1) A higher-order function tofun which when given an integer returns a polymorphic function, one which has type 'a->'a, meaning that it can be applied to values of any type, returning a value of the same type. An example of such a function is:
- fun id x = x;
val id = fn : 'a -> 'a
for example, id "cat" = "cat" and id () = (). The later value is of type unit, which is a type with only 1 value. Note that there is only 1 total function from unit to unit (namely, id or something equivalent). This underscores the difficulty with coming up with defining tofun: it returns a function of type 'a -> 'a, and other than the identity function it is hard to think of other functions. On the other hand -- such functions can fail to terminate or can raise an error and still have type 'a -> 'a.
2) fromfun is supposed to take a function of type 'a ->'a and return an integer. So e.g. fromfun id might evaluate to 0 (or if you want to get tricky it might never terminate or it might raise an error)
3) These are supposed to be inverses of each other so that, e.g. fromfun (tofun 5) needs to evaluate to 5.
Intuitively, this should be impossible in a sufficiently pure functional language. If it is possible in SML, my guess is that it would be by using some of the impure features of SML (which allow for side effects) to violate referential transparency. Or, the trick might involve raising and handling errors (which is also an impure feature of SML). If you find an answer which works in SML it would be interesting to see if it could be translated to the annoyingly pure functional language Haskell. My guess is that it wouldn't translate.
You can devise the following property:
fun prop_inverse f g n = (f o g) n = n
And with definitions for tofun and fromfun,
fun tofun n = ...
fun fromfun f = ...
You can test that they uphold the property:
val prop_test_1 =
List.all
(fn i => prop_inverse fromfun tofun i handle _ => false)
[0, ~1, 1, valOf Int.maxInt, valOf Int.minInt]
And as John suggests, those functions must be impure. I'd also go with exceptions.

Haskell IO Passes to Another Function

This question here is related to
Haskell Input Return Tuple
I wonder how we can passes the input from monad IO to another function in order to do some computation.
Actually what i want is something like
-- First Example
test = savefile investinput
-- Second Example
maxinvest :: a
maxinvest = liftM maximuminvest maxinvestinput
maxinvestinput :: IO()
maxinvestinput = do
str <- readFile "C:\\Invest.txt"
let cont = words str
let mytuple = converttuple cont
let myint = getint mytuple
putStrLn ""
-- Convert to Tuple
converttuple :: [String] -> [(String, Integer)]
converttuple [] = []
converttuple (x:y:z) = (x, read y):converttuple z
-- Get Integer
getint :: [(String, Integer)] -> [Integer]
getint [] = []
getint (x:xs) = snd (x) : getint xs
-- Search Maximum Invest
maximuminvest :: (Ord a) => [a] -> a
maximuminvest [] = error "Empty Invest Amount List"
maximuminvest [x] = x
maximuminvest (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maximuminvest xs
In the second example, the maxinvestinput is read from file and convert the data to the type maximuminvest expected.
Please help.
Thanks.
First, I think you're having some basic issues with understanding Haskell, so let's go through building this step by step. Hopefully you'll find this helpful. Some of it will just arrive at the code you have, and some of it will not, but it is a slowed-down version of what I'd be thinking about as I wrote this code. After that, I'll try to answer your one particular question.
I'm not quite sure what you want your program to do. I understand that you want a program which reads as input a file containing a list of people and their investments. However, I'm not sure what you want to do with it. You seem to (a) want a sensible data structure ([(String,Integer)]), but then (b) only use the integers, so I'll suppose that you want to do something with the strings too. Let's go through this. First, you want a function that can, given a list of integers, return the maximum. You call this maximuminvest, but this function is more general that just investments, so why not call it maximum? As it turns out, this function already exists. How could you know this? I recommend Hoogle—it's a Haskell search engine which lets you search both function names and types. You want a function from lists of integers to a single integer, so let's search for that. As it turns out, the first result is maximum, which is the more general version of what you want. But for learning purposes, let's suppose you want to write it yourself; in that case, your implementation is just fine.
Alright, now we can compute the maximum. But first, we need to construct our list. We're going to need a function of type [String] -> [(String,Integer)] to convert our formattingless list into a sensible one. Well, to get an integer from a string, we'll need to use read. Long story short, your current implementation of this is also fine, though I would (a) add an error case for the one-item list (or, if I were feeling nice, just have it return an empty list to ignore the final item of odd-length lists), and (b) use a name with a capital letter, so I could tell the words apart (and probably a different name):
tupledInvestors :: [String] -> [(String, Integer)]
tupledInvestors [] = []
tupledInvestors [_] = error "tupledInvestors: Odd-length list"
tupledInvestors (name:amt:rest) = (name, read amt) : tupledInvestors rest
Now that we have these, we can provide ourselves with a convenience function, maxInvestment :: [String] -> Integer. The only thing missing is the ability to go from the tupled list to a list of integers. There are several ways to solve this. One is the one you have, though that would be unusual in Haskell. A second would be to use map :: (a -> b) -> [a] -> [b]. This is a function which applies a function to every element of a list. Thus, your getint is equivalent to the simpler map snd. The nicest way would probably be to use Data.List.maximumBy :: :: (a -> a -> Ordering) -> [a] -> a. This is like maximum, but it allows you to use a comparison function of your own. And using Data.Ord.comparing :: Ord a => (b -> a) -> b -> b -> Ordering, things become nice. This function allows you to compare two arbitrary objects by converting them to something which can be compared. Thus, I would write
maxInvestment :: [String] -> Integer
maxInvestment = maximumBy (comparing snd) . tupledInvestors
Though you could also write maxInvestment = maximum . map snd . tupledInvestors.
Alright, now on to the IO. Your main function, then, wants to read from a specific file, compute the maximum investment, and print that out. One way to represent that is as a series of three distinct steps:
main :: IO ()
main = do dataStr <- readFile "C:\\Invest.txt"
let maxInv = maxInvestment $ words dataStr
print maxInv
(The $ operator, if you haven't seen it, is just function application, but with more convenient precedence; it has type (a -> b) -> a -> b, which should make sense.) But that let maxInv seems pretty pointless, so we can get rid of that:
main :: IO ()
main = do dataStr <- readFile "C:\\Invest.txt"
print . maxInvestment $ words dataStr
The ., if you haven't seen it yet, is function composition; f . g is the same as \x -> f (g x). (It has type (b -> c) -> (a -> b) -> a -> c, which should, with some thought, make sense.) Thus, f . g $ h x is the same as f (g (h x)), only easier to read.
Now, we were able to get rid of the let. What about the <-? For that, we can use the =<< :: Monad m => (a -> m b) -> m a -> m b operator. Note that it's almost like $, but with an m tainting almost everything. This allows us to take a monadic value (here, the readFile "C:\\Invest.txt" :: IO String), pass it to a function which turns a plain value into a monadic value, and get that monadic value. Thus, we have
main :: IO ()
main = print . maxInvestment . words =<< readFile "C:\\Invest.txt"
That should be clear, I hope, especially if you think of =<< as a monadic $.
I'm not sure what's happening with testfile; if you edit your question to reflect that, I'll try to update my answer.
One more thing. You said
I wonder how we can passes the input from monad IO to another function in order to do some computation.
As with everything in Haskell, this is a question of types. So let's puzzle through the types here. You have some function f :: a -> b and some monadic value m :: IO a. You want to use f to get a value of type b. This is impossible, as I explained in my answer to your other question; however, you can get something of type IO b. Thus, you need a function which takes your f and gives you a monadic version. In other words, something with type Monad m => (a -> b) -> (m a -> m b). If we plug that into Hoogle, the first result is Control.Monad.liftM, which has precisely that type signature. Thus, you can treat liftM as a slightly different "monadic $" than =<<: f `liftM` m applies f to the pure result of m (in accordance with whichever monad you're using) and returns the monadic result. The difference is that liftM takes a pure function on the left, and =<< takes a partially-monadic one.
Another way to write the same thing is with do-notation:
do x <- m
return $ f x
This says "get the x out of m, apply f to it, and lift the result back into the monad." This is the same as the statement return . f =<< m, which is precisely liftM again. First f performs a pure computation; its result is passed into return (via .), which lifts the pure value into the monad; and then this partially-monadic function is applied, via =<,, to m.
It's late, so I'm not sure how much sense that made. Let me try to sum it up. In short, there is no general way to leave a monad. When you want to perform computation on monadic values, you lift pure values (including functions) into the monad, and not the other way around; that could violate purity, which would be Very Bad™.
I hope that actually answered your question. Let me know if it didn't, so I can try to make it more helpful!
I'm not sure I understand your question, but I'll answer as best I can. I've simplified things a bit to get at the "meat" of the question, if I understand it correctly.
maxInvestInput :: IO [Integer]
maxInvestInput = liftM convertToIntegers (readFile "foo")
maximumInvest :: Ord a => [a] -> a
maximumInvest = blah blah blah
main = do
values <- maxInvestInput
print $ maximumInvest values
OR
main = liftM maximumInvest maxInvestInput >>= print