f# - What are the benefits of type inference? -
i'm started learn f#, , noticed 1 of major differences in syntax c# type inference used more in c#. presented 1 of benefits of f#. why type inference presented benefit?
imagine, have class hierarchy , code uses different classes it. strong typing allows detect classes used in method. type inference not obvious , have use hints understand, class used. there techniques exist make f# code more readable type inference?
this question assumes using object-oriented programming (e.g. complex class hierarchies) in f#. while can that, using oo concepts useful interoperability or wrapping f# functionality in .net library.
understanding code. type inference becomes more useful when write code in functional style. makes code shorter, helps understand going on. example, if write map function on list (the select method in linq):
let map f list = seq { el in list -> f el } the type inference tells function type is:
val map : f:('a -> 'b) -> list:seq<'a> -> seq<'b> this matches our expectations wanted write - argument f function turning values of type 'a values of type 'b , map function takes list of 'a values , produces list of 'b values. can use type inference check code expect.
generalization. automatic generalization (mentioned in comments) means above code automatically reusable possible. in c#, might write:
ienumerable<int> select(ienumerable<int> list, func<int, int> f) { foreach(int el in list) yield return f(el); } this method not generic - select works on collections of int values. there no reason why should restricted int - same code work types. type inference mechanism helps discover such generalizations.
more checking. finally, inference, f# language can more check more things if had write types explicitly. applies many aspects of language, best demonstrated using units of measure:
let l = 1000.0<meter> let s = 60.0<second> let speed = l/s the f# compiler infers speed has type float<meter/second> - understands how units of measure work , infers type including unit information. feature useful, hard use if had write units hand (because types long). in general, can use more precise types, because not have (always) type them.
Comments
Post a Comment