简体   繁体   中英

SUMPRODUCT in F# without variables

I have already done some searches, and this question is a duplicate of another post. I am posting this just for future reference.

Is it possible to define SUMPRODUCT without explicitly using variable names x, y?

Original Function:

let SUMPRODUCT x y = List.map2 (*) x y |> List.sum
SUMPRODUCT [1;4] [3;25]    // Result: 103

I was hoping to do this:

// CONTAINS ERROR!
let SUMPRODUCT = (List.map2 (*)) >> List.sum
// CONTAINS ERROR!

But F# comes back with an error.

I have already found the solution on another post, but if you have any suggestions please let me know. Thank you.

Function composition only works when the input function takes a single argument. However, in your example, the result of List.map2 (*) is a function that takes two separate arguments and so it cannot be easily composed with List.sum using >> .

There are various ways to work around this if you really want, but I would not do that. I think >> is nice in a few rare cases where it fits nicely, but trying to over-use it leads to unreadable mess.

In some functional languages, the core library defines helpers for turning function with two arguments into a function that takes a tuple and vice versa.

let uncurry f (x, y) = f x y
let curry f x y = f (x, y)

You could use those two to define your sumProduct like this:

let sumProduct = curry ((uncurry (List.map2 (*))) >> List.sum)

Now it is point-free and understanding it is a fun mental challenge, but for all practical purposes, nobody will be able to understand the code and it is also longer than your original explicit version:

let sumProduct x y = List.map2 (*) x y |> List.sum

According to this post:

What am I missing: is function composition with multiple arguments possible?

Sometimes "pointed" style code is better than "pointfree" style code, and there is no good way to unify the type difference of the original function to what I hope to achieve.

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