简体   繁体   中英

Haskell: Trouble with let statement

I'm trying to write a function in Haskell and I'm trying to start the function with two lets followed by the answer.

split :: (a -> b) -> (a -> c) -> a -> (b, c)
split x y z = 
    let first = ( x (y))
    let last = ( y (Z))
    (first, last)

I'm getting a "parse error on input 'let'" starting on the 2nd let statement. Why is this, and how can I fix this?

split :: (a -> b) -> (a -> c) -> a -> (b, c)

This says your first argument is a function from some type a to some type b and your second argument is a function from some type a to some type c .

split x y z = 

So x:: a -> b and y:: a -> c .

    let first = ( x (y))

That means you are trying to apply the function x to y but this won't work because x expects an argument of type a and y is of type a -> c . This is wrong.

    let last = ( y (Z))

There is no Z , check your capitalizations.

    (first, last)

Syntactically, you need an in . The syntax is:

let var1 = expr1
    var2 = expr2
in expr3WithVars1And2InScope

A small exception: When using do blocks you don't use in because that is implicitly the remainder of the do block.

There is no need here to work with a let , you can just make an expression with a simple 2-tuple:

split :: (a -> b) -> (a -> c) -> a -> (b, c)
split x y z = (x z, y z)

or you can simplify this to:

split :: (a -> b) -> (a -> c) -> a -> (b, c)
split x y = (,) <$> x <*> y

or even simpler:

import Control.Applicative(liftA2)

split :: (a -> b) -> (a -> c) -> a -> (b, c)
split = liftA2 (,)

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