Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# - create list with conditional elements

Tags:

list

f#

Consider this code

let a, b, c = ...
let mutable l = [a]

if conditionB then l <- b :: l
if conditionC then l <- c :: l

I feel as this goes against the language principles. Is this the correct way or am I missing something?

Edit: l is then just returned as a result

like image 222
aikixd Avatar asked Sep 29 '16 11:09

aikixd


2 Answers

Sequence expressions (https://learn.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/sequences) are quite practical for this purpose.

[ 
    if conditionC then yield c
    if conditionB then yield b
    yield a
]
like image 100
hvester Avatar answered Nov 15 '22 08:11

hvester


It is difficult to say without seeing the code in a larger context - but given just this snippet, you can avoid using mutation by defining a new version of the list with a different name:

let a, b, c = ...
let l1 = [a]
let l2 = if conditionB then b :: l1 else l1
let l3 = if conditionC then c :: l2 else l2

Here, we first define l1 which contains just the element a. Then we define a new lists l2 and l3, which contain additional elements depending on whether conditionB or conditionC holds (if none of them hold, we just copy reference to the original list l1 two times).

F# also has a feature called variable shadowing which lets you reuse the same name and hide the original value, so you could actually reuse the same name l for your lists - the following means exactly the same as the above code:

let a, b, c = ...
let l = [a]
let l = if conditionB then b :: l else l
let l = if conditionC then c :: l else l

And you can drop the last let l = if you just want to return the final list as the result.

like image 3
Tomas Petricek Avatar answered Nov 15 '22 10:11

Tomas Petricek