4 ms·
for example, getData() could be written something like: getData = fetchDataFromSource . validateData . ProcessData See http://www.haskell.org/haskellwiki/Fu
by joevandyk 16y ago
for example, getData() could be written something like:
getData = fetchDataFromSource . validateData . ProcessData
See http://www.haskell.org/haskellwiki/Function_composition http://www.haskell.org/haskellwiki/Function_composition
- lzm 16y agoHow would you handle validation errors in this case?
- lallysingh 16y agoTwo ways: (1) (avoid) something similar to exceptions; (2) (much better) your datatype has an 'invalid' value. See Maybe in haskell, or Option in Scala (I think that last one's right...).
- eru 16y agoWith error handling in Haskell your code would look like getData = fetchDataFromSource =<< validateData =<< ProcessData By the way, the original getData with (.) is backwards. It should be: getData = ProcessData . validateData . fetchDataFromSource
- CountSessine 16y agoIt would be specifically handled by the return type from validateData and the argument to ProcessData. It sounds clunky, but with an algebraic data type it would be fairly clean - just another pattern to match in ProcessData. For a simple example like this, that might be the cleanest solution. For anything more complicated (like recursive descent parsing), a processing chain like this is an ideal application for a monad, where the binding between functions would be customized to avoid calling ProcessData altogether.
- deleted 16y ago[deleted]
- ww520 16y agoCan you just use a callchain? function getData() { return processData(validateData(fetchDataFromSource())); }
- jerf 16y agoIt's not quite equivalent due to differences in the semantics; a functional language can far more easily do loop fusion: http://en.wikipedia.org/wiki/Loop_fusion http://en.wikipedia.org/wiki/Loop_fusion . An imperative language is likely to not even try in that situation, or in the case of a good C compiler, end up failing to do the optimization at the slightest hint of pointer use. In Haskell it's robust and can be composed many times.