Skip to main content
gamedev.net
🔒 Locked

Haskell - My brain is imploding :)

Started by mikeman Sep 9, 2006 at 6:33 PM 4 replies 1.4k views
Original Post
mikeman
mikeman
Ok, today I decided to do something dangerous and actually learn a purely functional language - Haskell. But I'm already stuck in function composition. Ok, so let's say we have 2 functions:

add x y = x + y
square x = x * x



Now, I want to create a new function that takes (x y), adds them and then squares the result. I understand I can't just do: (square.add) 2 3 because Haskell functions are curried. Haskell evaluates the result of "add 2", which is of type int->int and passes it to square which needs int, so it won't work. I can do: (square.add 2) 3 but what I really want the created function to take 2 arguments. So I see that I must do : ((square.).add) 2 3 Haskell evaluates "add 2" and passes the result to the composition function (.), which creates the function (square.add 2) and the rest works like in the previous example. But beyond that, I'm stuck. What if "add" had 3,4 or more parameters? How should I write it then?(if you can, do some explaining of your solution) Thanks in advance.
mikeman
mikeman
Ok, thanks very much :) Meanwhile though, I think I figured out how to do it with composition(not that I will ever use it):

(1) when g has 1 argument:
(f.g) 1

(2) with 2 arguments:
( (f.).g ) 1 2

(3) with 3 arguments:
( ((f.).).g ) 1 2 3

(4) with 4 arguments:
( (((f.).).).g ) 1 2 3 4

And so on and so on... I don't pretend that I can understand what (3),(4) and beyond do upon looking at them(lol), I just figured out the pattern. It's like creating "places" where 'g'(first g 1, then (g 1)2, then (g 1 2)3 and so on) can be evaluated until it can be composited with 'f'.
TheAdmiral
TheAdmiral
The composition operator is there to make things easier, but sometimes I find it just gets confusing, particularly if your readers are used to imperative languages.
I don't recommend that you do away with the . altogether, but should you need to, you can use parentheses in the same way you can in most imperative languages:

AddThenSquare :: Num a => a -> a -> a
AddThenSquare x y = square (add (x y))

Regards
Admiral
Ring3 Circus - Diary of a programmer, journal of a hacker.
Flarelocke
Flarelocke
There was something on Haskell-cafe recently about this:

You're looking for a point-free style version of this function:
f x y = square (add x y)

so the derivation goes like this:
f x y = square . (add x) y                -- definition of compositionf x   = (square .) (add x)                -- change to slice and eta reducef x   = ((square .) . add) x              -- another definition of compositionf     = (square .) . add                  -- eta reduction


More likely, someone would just use:
curry (square . uncurry add)
---New infokeeps brain running;must gas up!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.