[Haskell-cafe] Lambda-case / lambda-if

Jan Christiansen jac at informatik.uni-kiel.de
Sat Oct 2 15:27:01 EDT 2010


On 02.10.2010, at 20:35, Henning Thielemann wrote:

>
> On Sat, 2 Oct 2010, Colin Paul Adams wrote:

>>   Prelude> (if then "Haskell" else "Cafe") False
>>   Max> "Cafe"
>>
>> My reaction is to ask:
>>
>> Can you write this as:
>>
>> (if then else) False  "Haskell"  "Cafe"
>>
>> ?
>
> Sure:
>
> ifThenElse :: Bool -> a -> a -> a
> ifThenElse True  x _ = x
> ifThenElse False _ y = y
>
> Prelude> ifThenElse False "Haskell" "Cafe"


You can use a similar approach for case expressions ; )


import Prelude hiding ( catch )
import System.IO.Unsafe ( unsafePerformIO )
import Control.Exception ( catch, evaluate, PatternMatchFail )


caseOf :: a -> [a -> b] -> b
caseOf x = unsafePerformIO . firstMatch . map ($x)

firstMatch :: [a] -> IO a
firstMatch (x:xs) = catch (evaluate x) (handlePatternFail (firstMatch  
xs))

handlePatternFail :: a -> PatternMatchFail -> a
handlePatternFail x _ = x


test = (flip caseOf [\1 -> "One", \_ -> "Not-one"]) 1


Well, to tell the truth this does not work correctly as the following  
example shows.

test2 = (flip caseOf [\1 -> ((\2 -> "One") 3), \_ -> "Not-one"]) 1


More information about the Haskell-Cafe mailing list