Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between lists, arrays, and tuples in F#?

Tags:

f#

What is difference between lists, arrays, and tuples in F#? Is it easy to convert between them when required? They seem all similar in spirit, so what do actually I need to know that lets me understand when to use one versus another?

like image 416
Tim Lovell-Smith Avatar asked Feb 16 '15 22:02

Tim Lovell-Smith


1 Answers

A tuple is a grouping of unnamed, ordered values. Each value in a tuple does not need to be the same type, which means you can have a tuple defined like:

let someTuple = (1, "foo", 42.3)

This would create a tuple containing an int, string, and float value.

A list is an ordered collection of values of the same type which is immutable. This is probably the most common collection type used in functional programming, as it's completely immutable and has a lot of functionality for creating lists built on top of previously created lists, which allows you to make collections that "grow" (they're actually new collections, however, as the lists are immutable).

An array is a fixed size, mutable collection. They are very efficient to create, but must always be a single type.

Is it easy to convert between them when required?

It's very easy to convert between lists and arrays. You can use List.ofArray, List.toArray, Array.ofList, and Array.toList to convert between the types.

Converting from tuple to array or list is not common, and not always possible, as tuples allow multiple types to be stored within them.

They seem all similar in spirit, so what do actually I need to know that lets me understand when to use one versus another?

Lists and arrays are both used for collections. In general, you'll want to prefer lists if you're going to be making lists that "grow", as making a new list comprised of an element + the original list is much more efficent than doing the same thing with an array.

Arrays are often used for higher performance scenarios (they have better memory locality, are more space efficient, etc), but are mutable and fixed size, so they're often not ideal when you're trying to work with constructing collections.

Tuples are typically used for completely different scenarios. The most common use case for tuples is to pass around multiple items as one value. This happens automatically when using framework methods that have out parameters, for example, so you'll see use cases like:

let (success, value) = int.TryParse(someString)

In this case, the tuple is automatically created and then pattern matched to extract the values in a single line of code. Instead of thinking of a tuple as a "collection", it's more of a way to hold multiple values, often of different types, together.

like image 158
Reed Copsey Avatar answered Sep 18 '22 23:09

Reed Copsey