Home > Net >  Haskell: Trouble with let statement
Haskell: Trouble with let statement

Time:09-12

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?

CodePudding user response:

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.

CodePudding user response:

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 (,)
  • Related