Keeping partially applied function generic

前端 未结 3 1062
萌比男神i
萌比男神i 2020-12-19 07:06

Is it possible to partially apply a function such as bprintf and prevent it from being restricted based on its initial use?

I\'d like to do the followin

3条回答
  •  借酒劲吻你
    2020-12-19 07:22

    The aspect of F# that's causing this is called value restriction. You can see that if you enter just the two let declarations to F# Interactive (so that the compiler doesn't infer the type from the first use):

    > let builder = new System.Text.StringBuilder() 
      let append = Printf.bprintf builder ;;
    

    error FS0030: Value restriction. The value 'append' has been inferred to have generic type val append : ('_a -> '_b) when '_a :> Printf.BuilderFormat<'_b> Either make the arguments to 'append' explicit or, if you do not intend for it to be generic, add a type annotation.

    There is an excellent article by Dmitry Lomov from the F# team which explains it in detail. As the article suggests, one solution is to add explicit type parameter declaration:

    let builder = new System.Text.StringBuilder() 
    let append<'T> : Printf.BuilderFormat<'T> -> 'T = Printf.bprintf builder 
    append "%i" 10 
    append "%s" "Hello"
    

    This will work just fine.

提交回复
热议问题