Answer the question
In order to leave comments, you need to log in
What is the order of evaluation of expressions in this code?
There is this code in Haskell:
instance FromJSON Movie where
parseJSON (Object o) = do
movieValue <- head <$> o .: "movies"
Movie <$> movieValue .: "id" <*> movieValue .: "title"
parseJSON _ = mzero
Movie <$> movieValue .: "id" <*> movieValue .: "title"
head <$> o .: "movies"
Answer the question
In order to leave comments, you need to log in
movieValue .: "id"
creates a parser that reads id. Applied to it Movie <$>
creates a parser that will apply the Movie constructor to id, as a result of such a parser will be a function from one missing argument.
Also movieValue .: "title"
creates a parser that reads the title.
If it were just a function and a value, one could apply one to the other, in our case using <*>
, which will create a parser that combines both parsers passed to it, applying the result of one to the result of the other. Moreover, since both parsers are independent, they can be executed in any order. But in this case, from left to right. You can check like this:
Answer:
If it had evaluated the right argument first, the error would have been different - b not found.
What do you mean by order of evaluation?
Haskell is a lazy language, it doesn't compute until it's needed. In this line, you, consider, created a thunk, which, when it is pulled, will begin to calculate something there. In this example, when yanked, it will start to figure out if the parser is failing, for which you will have to make sure that the parsers included in it are not failing. The order can be any, but the author of the library most likely made the order natural.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question