繁体   English   中英

OCaml:使用一个范围来构建列表,该范围的大小ID由从float转换为int的整数确定

[英]OCaml: building a list using a range in which the size id determined by a int cast from a float

我正在尝试在OCaml中构建一个列表,该列表从返回从float转换为int的函数的函数中获取其结束范围变量:

    #require "batteries"
    #require "pa_comprehension"
    #require "core_kernel"
open Batteries
open Core_kernel

let factor_of num fact = num mod fact == 0 ;;

let limit num =  Float.to_int (floor (sqrt num) ) ;;

由于以下原因,未执行此列表的填充:

Error: This expression has type int but an expression was expected of type [< Downto | To ]

在两个(好吃的)电池列表中理解:

[? List: x | x <- 0--(limit num) ; factor_of num x ?] ;;

以及(略少但仍很易读)core_kernel List构造函数:

List.(range 0 (limit num) |> filter ~f:( fun x -> factor_of num x) );;

我在想limit num的返回值被困在提供Float.to_int函数的(邪恶)单子内部。 当使用Float.int_of_float时,类型签名也相同:

utop # Float.to_int;;
- : float -> int = <fun>

那么...如何将我的int从单子中“取出”,或者,如果这不是问题,那是怎么回事,以及如何转换为可以这种方式使用的实际int

另外,有人可以指出我一个体面的“这些东西到底是什么:莫纳德斯”微妙的大脑教程吗? 我不知所措。

更新:该错误不是由任何单调行为引起的(或根本没有使用),这是由于不正确地使用了infix运算符(mod)以及我对功能思维中的其他一些怪癖造成的,而我对此并不完全理解。 我不确定这篇文章是否应该仍然存在,但是也许这是您进入功能范式时可能犯的错误的一个例子……?

我设法找到问题的根源。 经过深思熟虑和深夜:

该错误不是由任何单子行为引起的(或者根本就没有使用单子行为)引起的,这是由于错误地使用了infix运算符(mod)和功能性思考中的其他一些怪癖引起的,而我对此并不完全理解。 我不确定这篇文章是否应该仍然存在,但是也许这是您进入功能范式时可能犯的错误的一个例子……?

感谢帮助我解决问题的Str帮助我改变主意。 Joe Gob还指出了代码中的主要问题。 根据我的函数所需的类型,在float和int之间进行更多转换。

这是更正的代码(deps.ml是需求文件):

   #use "deps.ml";;
open Batteries
open Core_kernel

let factor_of num fact = num mod fact == 0 ;;

let limit num = 2 * Float.to_int (floor (sqrt num)) ;;

let factor_list_of num =
  [? List: x | x <- 1--(limit (Int.to_float num)) ; factor_of num x ?]

let sum_factors num = ( List.fold_right (+) (factor_list_of num) 0 )

let is_perfect num = sum_factors num == num
let is_abundant num = sum_factors num > num
let is_deficient num = sum_factors num < num

基本上,我已经被Ruby宠坏了,但是我强烈建议rubyists接受ocaml,它的风格与功能语言的ruby代码最接近。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM