Hide this comment

The problem is a function without a function isn't a function its just a value. So functions that you don't want to have any parameters have a special parameter called "unit", which is represented by a pair of brackets - ().

So you need to write:

1
2
3
4
5
6
#light
let loop2 n f = 
    for a in 1 to n do 
        f() 

loop2 100 (fun () -> printfn "Hello World") 
By on 1/22/2008 4:58 AM ()Reply
Hide this comment

Ah, got it.

Now I can also get to the 3rd step i was trying to reach:

1
2
3
4
5
6
7
8
9
10
11
12
#light

let loop3 n f = 

....for a in 1 to n do 

........f a

loop3 100 (fun a -> printfn "Hello World %i" a)        

loop3 100 (fun _ -> printfn "Hello World")
By on 1/22/2008 5:10 AM ()Reply
Hide this comment

Okay -- moving a little further into my tinkering here, i've got another question...

using loop2 again:

1
2
3
4
5
6
7
8
#light

let loop2 n f = 

....for a in 1..n do 

........f a 

i've made a "higher order function" called loop100

let loop100 = loop2 100 //loop2 is partially applied

hence:

1
2
loop100 (fun _ -> printfn "Hello World") 

Gives me 100 times "Hello World"

All good so far.

Now I want to create a new higher order function,

1
2
loop100Who

Such that:

1
2
loop100Who "Fred"

returns:

Hello Fred

Hello Fred

Hello Fred (so on 100 times)

I can't quite craft a loop100Who that does what I want.

I know it will include 'printfn "Hello %s" name'

but my attempts so far do not type check, let alone work as desired...

1
2
3
4
5
6
7
8
9
10
//Some of my dodgy attempts include:

//let loop100Who name = (fun name -> (loop100 (fun _ name -> printfn "Hello %s" name)))

//let loop100Who name = (loop100 (fun _ -> printfn "Hello %s" name) name)

//let loop100Who name = loop100 (fun _ name -> printfn "Hello %s" name) name

//let loop100Who name = loop100 (fun name -> (fun _ -> printfn "Hello %s" name) )

Again -- any help very much appreciated ;-)

By on 1/22/2008 5:56 AM ()Reply
Hide this comment

You were very close, its actually simpler that you think. The name is already caught in the lambda so there's no need to try and pass it in again.

1
2
3
4
5
6
7
8
#light
let loop2 n f = 
    for a in 1..n do 
        f a 
        
let loop100 = loop2 100 

let loop100Who name = loop100 (fun _ -> printfn "Hello %s" name)
By on 1/22/2008 7:44 AM ()Reply
Hide this comment

Ah! thanks Robert.

By on 1/22/2008 1:56 PM ()Reply
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper

Logging in...