Idiom of using in F#

本文通过一个HTTP请求的示例,展示了F#语言如何简化代码并确保资源安全释放。使用了[b]using[/b]函数使得代码更加简洁安全。
In Don Syme's [url=http://blogs.msdn.com/dsyme/archive/2006/12/18/DraftChaptersUpdateDec2006.aspx]excellent book drafts[/url] of his upcoming book [i]Expert F#[/i], the following code is used to demonstrate the quickness and easiness of F# interactive development.

[code]
> let req = WebRequest.Create("http://www.microsoft.com");;
val req : WebRequest
> let resp = req.GetResponse();;
val resp : WebResponse
> let stream = resp.GetResponseStream();;
val stream : Stream
> let reader = new StreamReader(stream) ;;
val reader : StreamReader
> let html = reader.ReadToEnd();;
val html : string = "<html>...</html>"
[/code]

However, writing codes in such way would be too imperative. By using the idiomatic [b]using[/b] function, we can write it in a more concise and safer form:

[code]#light
let http (url: string) =
let req = WebRequest.Create(url)
using (req.GetResponse())
(fun res -> using (res.GetResponseStream())
(fun stream -> let reader = new StreamReader(stream)
reader.ReadToEnd())) [/code]

The arguments of [b]using[/b] are:
[code]val it : 'a -> ('a -> 'b) -> 'b when 'a :> IDisposable = <fun:clo@0>[/code]
Clearly, the first argument requires a resource that implements the IDisposable interface ( [b]:>[/b] is a special operator in F# for up-casting); then [b]using[/b] will feed the resource to a function to process further and finally will guarantee to release the resource when everything is done.
File "<string>", line 1, in <module> from multiprocessing.spawn import spawn_main; spawn_main(parent_pid=26856, pipe_handle=1552) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\spawn.py", line 122, in spawn_main exitcode = _main(fd, parent_sentinel) File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\spawn.py", line 131, in _main prepare(preparation_data) ~~~~~~~^^^^^^^^^^^^^^^^^^ File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\spawn.py", line 246, in prepare _fixup_main_from_path(data['init_main_from_path']) ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\spawn.py", line 297, in _fixup_main_from_path main_content = runpy.run_path(main_path, run_name="__mp_main__") File "<frozen runpy>", line 287, in run_path File "<frozen runpy>", line 98, in _run_module_code File "<frozen runpy>", line 88, in _run_code File "f:\yolov8\ultralytics-main\test.py", line 8, in <module> model.train(data='yolo_bvn.yaml',workers=1,epochs=1, batch=16) ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "f:\yolov8\ultralytics-main\ultralytics\engine\model.py", line 799, in train self.trainer.train() ~~~~~~~~~~~~~~~~~~^^ File "f:\yolov8\ultralytics-main\ultralytics\engine\trainer.py", line 227, in train self._do_train(world_size) ~~~~~~~~~~~~~~^^^^^^^^^^^^ File "f:\yolov8\ultralytics-main\ultralytics\engine\trainer.py", line 348, in _do_train self._setup_train(world_size) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^ File "f:\yolov8\ultralytics-main\ultralytics\engine\trainer.py", line 307, in _setup_train self.train_loader = self.get_dataloader( ~~~~~~~~~~~~~~~~~~~^ self.data["train"], batch_size=batch_size, rank=LOCAL_RANK, mode="train" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "f:\yolov8\ultralytics-main\ultralytics\models\yolo\detect\train.py", line 90, in get_dataloader return build_dataloader(dataset, batch_size, workers, shuffle, rank) # return dataloader File "f:\yolov8\ultralytics-main\ultralytics\data\build.py", line 183, in build_dataloader return InfiniteDataLoader( dataset=dataset, ...<8 lines>... drop_last=drop_last, ) File "f:\yolov8\ultralytics-main\ultralytics\data\build.py", line 58, in __init__ self.iterator = super().__iter__() ~~~~~~~~~~~~~~~~^^ File "F:\Minicond3\envs\yolov8\Lib\site-packages\torch\utils\data\dataloader.py", line 493, in __iter__ return self._get_iterator() ~~~~~~~~~~~~~~~~~~^^ File "F:\Minicond3\envs\yolov8\Lib\site-packages\torch\utils\data\dataloader.py", line 424, in _get_iterator return _MultiProcessingDataLoaderIter(self) File "F:\Minicond3\envs\yolov8\Lib\site-packages\torch\utils\data\dataloader.py", line 1171, in __init__ w.start() ~~~~~~~^^ File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\process.py", line 121, in start self._popen = self._Popen(self) ~~~~~~~~~~~^^^^^^ File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\context.py", line 224, in _Popen return _default_context.get_context().Process._Popen(process_obj) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^ File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\context.py", line 337, in _Popen return Popen(process_obj) File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\popen_spawn_win32.py", line 47, in __init__ prep_data = spawn.get_preparation_data(process_obj._name) File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\spawn.py", line 164, in get_preparation_data _check_not_importing_main() ~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "F:\Minicond3\envs\yolov8\Lib\multiprocessing\spawn.py", line 140, in _check_not_importing_main raise RuntimeError(''' ...<16 lines>... ''') RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable. To fix this issue, refer to the "Safe importing of main module" section in https://docs.python.org/3/library/multiprocessing.html
07-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值