Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# function running without being called

Tags:

.net

f#

This code

open System.Threading

let duration = 1000

module SequentialExample =
    let private someTask item =
        printfn "oh god why"
        Thread.Sleep(duration)
        item + " was computed"

    let private items = [
        "foo"
        "bar"
        "baz"
    ]

    let getComputedItems = 
        printfn "heh"
        [for item in items -> someTask item]
        |> Array.ofList

module ParallelExample =
    let private someTask item =
        printfn "that's ok"
        Thread.Sleep(duration)
        item + " was computed"

    let private items = [
        "foo"
        "bar"
        "baz"
    ]

    let getComputedItems = 
        Async.Parallel [for item in items -> async { return someTask item }]
        |> Async.RunSynchronously

[<EntryPoint>]
let main args =
    ParallelExample.getComputedItems |> ignore
    0

Has the following output:

heh
oh god why
oh god why
oh god why
that's ok
that's ok
that's ok

If I'm calling ParallelExample module, why is F# running the code in SequentialExample module?

What am I doing wrong?

like image 433
Gabriel Avatar asked Dec 24 '22 05:12

Gabriel


1 Answers

As John Palmer said in comments, let getComputedItems = ... is actually a value, not a function, because a function has to take an argument.

To make it a function, one have to declare it like let getComputedItems () = ....

like image 90
Gabriel Avatar answered Jan 05 '23 04:01

Gabriel