Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to keep in mind while learning F#, having learned Scheme

Tags:

f#

scheme

I'm quite interested in learning F#.

My only experience with functional languages has been 2 introductory courses on Scheme in college.

Are there any things that I should keep in mind while learning F#, having previously learned Scheme? Any differences in methodologies, gotchas or other things that might give me trouble?

like image 745
Zaven Nahapetyan Avatar asked Dec 08 '10 05:12

Zaven Nahapetyan


Video Answer


1 Answers

Are there any things that I should keep in mind while learning F#, having previously learned Scheme? Any differences in methodologies, gotchas or other things that might give me trouble?

Static typing is the major difference between Scheme and F#. This facilitates a style called typeful programming where the type system is used to encode constraints about functions and data such that the compiler proves these aspects of the program correct at compile time and any violations of the constraints are caught immediately.

For example, a sequence of one or more elements of the same type might be conveyed by a value of the following type:

type list1<'a> = List1 of 'a * 'a list

let xs = List1(1, [])
let ys = List1(2, [3; 4])

The compiler now guarantees that any attempt to use an empty one of these sequences will be caught at compile time as an error.

Now, the reduce function makes no sense on an empty sequence so the built-in implementation for lists barfs at run-time with an exception if it encounters an empty sequence:

> List.reduce (+) [];;
System.ArgumentException: The input list was empty.
Parameter name: list
   at Microsoft.FSharp.Collections.ListModule.Reduce[T](FSharpFunc`2 reduction, FSharpList`1 list)
   at <StartupCode$FSI_0271>.$FSI_0271.main@()
Stopped due to error

With our new sequence of one or more elements, we can now write a reduce function that never barfs at run-time with an exception because its input is guaranteed by the type system to be non-empty:

let rec reduce f = function
  | List1(x, []) -> x
  | List1(x0, x1::xs) -> f x0 (reduce f (List1(x1, xs)))

This is a great way to improve the reliability of software by eliminating sources of run-time errors and it is something that dynamically typed languages like Scheme cannot even begin to do.

like image 115
J D Avatar answered Sep 18 '22 12:09

J D