Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make better Haskell function

Tags:

haskell

I have following Haskell function

fun::Vertex3 GLfloat -> Vertex3 GLfloat ->  Vertex3 GLfloat
fun (Vertex3 x0 y0 z0) (Vertex3 x1 y1 z1) = do sth here
        where
            p0 = (Vertex3 x0 y0 z0)
            p1 = (Vertex3 x1 y1 z1)
            p = p0 + p1

I'm wondering whether there is a way to not repeat (Vertex3 x0 y0 z0) (Vertex3 x1 y1 z1) inside the code

I'm looking for some thing like:

fun::Vertex3 GLfloat -> Vertex3 GLfloat ->  Vertex3 GLfloat
fun p0 p1 = do sth here
    where 
        p0 = (Vertex3 x0 y0 z0)
        p1 = (Vertex3 x1 y1 z1)
        p = p0 + p1
like image 309
Aron Lee Avatar asked Jan 26 '26 11:01

Aron Lee


1 Answers

Yes, you can use an as-pattern [AGItH'98]:

fun::Vertex3 GLfloat -> Vertex3 GLfloat -> Vertex3 GLfloat
fun p0@(Vertex3 x0 y0 z0) p1@(Vertex3 x1 y1 z1) = do sth here
        where p = p0 + p1

Here we thus have a reference to both the argument p0, as well as elements in the data constructor (x0, y0, z0).

These as-patterns can be used at different levels in the pattern.

like image 78
Willem Van Onsem Avatar answered Jan 28 '26 05:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!