Point-free style with objects/records in F#

本秂侑毒 提交于 2019-12-21 20:12:23

问题


I'm getting stymied by the way "dot notation" works with objects and records when trying to program in a point-free functional style (which I think is a great, concise way to use a functional language that curries by default).

Is there an operator or function I'm missing that lets me do something like: (.) object method instead of object.method?

(From what I was reading about the new ? operator, I think it works like this. Except it requires definition and gets into the whole dynamic binding thing, which I don't think I need.)

In other words, can I apply a method to its object as an argument like I would apply a normal function to its argument?


回答1:


Short answer: no.

Longer answer: you can of course create let-bound functions in a module that call a method on a given type... For example in the code

let l = [1;2;3]
let h1 = l.Head 
let h2 = List.hd l

there is a sense in which "List.hd" is the version of what you want for ".Head on a list". Or locally, you can always do e.g.

let AnotherWay = (fun (l:list<_>) -> l.Head)
let h3 = AnotherWay l

But there is nothing general, since there is no good way to 'name' an arbitrary instance method on a given type; 'AnotherWay' shows a way to "make a function out of the 'Head' property on a 'list<_>' object", but you need such boilerplate for every instance method you want to treat as a first-class function value.

I have suggested creating a language construct to generalize this:

With regards to language design suggestions, what if

 SomeType..Foo optArgs   // note *two* dots 

meant

 fun (x : SomeType) -> x.Foo optArgs 

?

In which case you could write

list<_>..Head

as a way to 'functionize' this instance property, but if we ever do anything in that arena in F#, it would be post-VS2010.




回答2:


If I understand your question correctly, the answer is: no you can't. Dot (.) is not an operator in F#, it is built into the language, so can't be used as function.



来源:https://stackoverflow.com/questions/943405/point-free-style-with-objects-records-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!