Chi*_*del 5 ocaml functional-programming
我正在自学OCaml,我正在练习的主要资源是康奈尔从3110课程中提供的一些问题.其中一个问题是编写一个函数来反转int(即:1234 - > 4321,-1234 - > -4321,2 - > 2,-10 - > -1等).
我有一个有效的解决方案,但我担心它不完全是惯用的OCaml:
let rev_int (i : int) : int =
let rec power cnt value =
if value / 10 = 0 then cnt
else power (10 * cnt) (value/10) in
let rec aux pow temp value =
if value <> 0 then aux (pow/10) (temp + (value mod 10 * pow)) (value / 10)
else temp in
aux (power 1 i) 0 i
Run Code Online (Sandbox Code Playgroud)
据我所知,它在所有情况下都能正常工作,但它对我来说似乎是非常"非OCaml",特别是因为我使用两个内部函数运行了两次int的长度.所以我只是想知道是否有更多的"OCaml"方式来做到这一点.
I would say, that the following is idiomatic enough.
(* [rev x] returns such value [y] that its decimal representation
is a reverse of decimal representation of [x], e.g.,
[rev 12345 = 54321] *)
let rev n =
let rec loop acc n =
if n = 0 then acc
else loop (acc * 10 + n mod 10) (n / 10) in
loop 0 n
Run Code Online (Sandbox Code Playgroud)
But as Jeffrey said in a comment, your solution is quite idiomatic, although not the nicest one.
Btw, my own style, would be to write like this:
let rev n =
let rec loop acc = function
| 0 -> acc
| n -> loop (acc * 10 + n mod 10) (n / 10) in
loop 0 n
Run Code Online (Sandbox Code Playgroud)
因为我更喜欢模式匹配if/then/else。但这是我个人品味的问题。
| 归档时间: |
|
| 查看次数: |
721 次 |
| 最近记录: |