简体   繁体   中英

Definition of (&&) using Lambda Expressions

I was given the following questions:

1.

True && True = True  
_ && _ = False

I wrote this as a conditional expression:

(&&) a b = if a then  
if b then True else False 
else False 

2.

True && b = b  
False && _ = False

I wrote this as a conditional expression:

(&&) a b = if a then b else False

I am trying to write these two definitions given for (&&) in lambda expression, but I not exactly sure where to start or how to do it.

I won't just straight up write the answer because this seems like an assignment / homework of some sort. So I'll just explain a bit how lambdas work.

Let's take a basic lambda and break it down: \\ab -> a

To the left side of the arrow (in this case ab) we have the arguments. These are what is passed to the lambda.

On the right side of the arrow we have the output (in this case a). So what this lambda does is takes two values and gives you the first one.

The output could be any expression for example if we restrict a and b to be numbers then we could have myLambda = \\ab -> a + b so myLambda 1 2 would output 3.

So to convert your definitions into lambdas just take your if then else statements and have those as the expression after the arrow in the lambda.

You could also use the pattern matching used in the initial definitions you gave and convert that to a lambda with a case of statement. This takes a value between the case and of and then you provide various expressions to be outputted depending on what the value was eg

case a of
    True -> something1
    False -> something2

So to put that in a lambda would give you:

\a b -> case a of
    value1 -> something1
    value2 -> something2

For the sake of completeness I will mention that there is a LambdaCase language extension that allows you to simplify:

\a -> case a of
    value1 -> something1
    value2 -> something2

to

\case
    value1 -> something1
    value2 -> something2

But this is not necessary and I certainly wouldn't worry about it as a beginner.

I hope this helps, feel free to ask for clarification :)

Generally, if

foo bar baz = quux

then the two definitions

foo = \bar baz -> quux -- OR
foo = \bar -> \baz -> quux

are essentially identical to the original (up to some language warts that can be worked around by giving an explicit type signature). You can choose whichever one you like better. So,

(&&) a b = if a then b else False

can also be written as:

(&&) = \a b -> if a then b else False

Can you work out how to do the other one following this same pattern?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM