Haskell: Implementing "if"

Posted by Daniel Lyons Mon, 11 Dec 2006 22:08:54 GMT

It just occurred to me, Haskell is the only language I know of in which one can implement if without using if (or cond, or whatever):

my_if True x _ = x
my_if False _ y = y

A test:

*Main> my_if True (putStrLn "Hello, World!") (putStrLn "Goodbye, World!")
Hello, World!
*Main> my_if False (putStrLn "Hello, World!") (putStrLn "Goodbye, World!")
Goodbye, World!
*Main> my_if (2 == 2) (putStrLn "Hello, World!") (putStrLn "Goodbye, World!")
Hello, World!
*Main> my_if (3 == 2) (putStrLn "Hello, World!") (putStrLn "Goodbye, World!")
Goodbye, World!

Neat!

Of course I’m sure Lisp could do this with a macro (and if or cond), but to have this in the very fabric of the language is kind of nice.

Tags , , ,  | 3 comments

Comments

  1. Avatar Jules said about 1 month later:

    If actually is implemented like this in Smalltalk. You have two objects: true and false. These have a method ifTrue: [ code here ].

    So:

    false ifTrue: [nothing will happen]
    true ifTrue: [this code will be executed]
    

    The ifTrue method for the false object does nothing, and the ifTrue method of the true object evaluates its argument.

    It doesn’t even use special sugar (like Haskell), just normal message send syntax.

  2. Avatar Jules said about 1 month later:

    If actually is implemented like this in Smalltalk. You have two objects: true and false. These have a method ifTrue: [ code here ].

    So:

    false ifTrue: [nothing will happen]
    true ifTrue: [this code will be executed]
    

    The ifTrue method for the false object does nothing, and the ifTrue method of the true object evaluates its argument.

    It doesn’t even use special sugar (like Haskell), just normal message send syntax.

  3. Avatar Jules said about 1 month later:

    btw you really have to add a spinner to indicate that the submit button works ;-)

(leave url/email »)

   Comment Markup Help Preview comment