Suppose I have some type
data Result = Fail | Success deriving (Show)
expressing result of some operation and another arbitrary type
data MyData
and some function which processes the data
someAction :: MyData -> Result
someAction = if ... then Success else Fail
I need a wrapper function formatAction which calls someAction with MyData and formats the result of processing using case statement. Something like that:
formatAction :: MyData -> String
formatAction = let res = someAction in
case res of
Success -> "OK"
Fail -> "Fail"
It's not a valid code, but I can't undestand how to use result of the function with 'case' expression. Any idea?
Actually I meant a piece of code like that:
data Result = Fail | Success
data SomeData = SDS | SDF
doSomeWork' :: SomeData -> Result
doSomeWork' SDS = Success
doSomeWork' _ = Fail
processData :: SomeData -> String
processData = let res = doSomeWork' in
case res of
Success -> "OK"
Fail -> "Fail"
It doesn't compile with the message:
D:\Work\Haskell\revRange.hs:16:17:
Couldn't match expected type SomeData -> Result'
with actual type
Result'
In the pattern: Success
In a case alternative: Success -> "OK"
In the expression:
case res of {
Success -> "OK"
Fail -> "Fail" }
D:\Work\Haskell\revRange.hs:16:28:
Couldn't match expected type SomeData -> String'
with actual type
[Char]'
In the expression: "OK"
In a case alternative: Success -> "OK"
In the expression:
case res of {
Success -> "OK"
Fail -> "Fail" }
D:\Work\Haskell\revRange.hs:17:17:
Couldn't match expected type SomeData -> Result'
with actual type
Result'
In the pattern: Fail
In a case alternative: Fail -> "Fail"
In the expression:
case res of {
Success -> "OK"
Fail -> "Fail" }
D:\Work\Haskell\revRange.hs:17:25:
Couldn't match expected type SomeData -> String'
with actual type
[Char]'
In the expression: "Fail"
In a case alternative: Fail -> "Fail"
In the expression:
case res of {
Success -> "OK"
Fail -> "Fail" }
Just can't catch how to match the result to the patterns.
Show
instance, you can implement it yourself (Success
mapped to"OK"
, of source) and defineformatAction = show . someAction
. – zakyggapsMyData -> String' with actual type
[Char]' In the expression: "OK" In a case alternative: Success -> "OK" In the expression: case res of { Success -> "OK" Fail -> "Fail" } – BarbedWireprocessData
does not take any arguments, and does not forward them todoSomeWork'
. Hence,res
is a function, not aSomeData
value, and you can't pattern match on that. Simon H. below did it correctly. – chi