【问题标题】:OCaml Triple every number in a list of integersOCaml 将整数列表中的每个数字三倍
【发布时间】:2017-03-22 18:08:16
【问题描述】:

所以我需要编写一个函数,将整数列表中的每个数字加三倍

这是我目前所拥有的:

let number =  [1; 2; 3; 4];;

let rec print_list_int myList = match myList with
| [] -> print_endline "This is the end of the int list!"
| head::body -> 
begin
print_int head * 3; 
print_endline "";
print_list_int body *3
end
;;

print_list_int number;; 

它似乎没有做任何有用的事情,我哪里出错了有什么想法吗?需要它输出,但它也不这样做。提前致谢! :)

【问题讨论】:

    标签: list functional-programming ocaml


    【解决方案1】:

    这个表达式:

    print_int head * 3
    

    是这样解释的:

    (print_int head) * 3
    

    因为函数调用(应用程序)具有高优先级。您需要像这样用括号括起来:

    print_int (head * 3)
    

    下面的类似情况是一个不同的问题:(print_list_int body) * 3 没有意义,但print_list_int (body * 3) 也没有意义。您不能将列表乘以 3。但是,您不需要在此调用中进行乘法运算。 print_list_int 函数将(递归地)为你做乘法。

    更新

    如果我做出上面提示的更改,我会在 OCaml 顶层看到这一点:

    val print_list_int : int list -> unit = <fun>
    # print_list_int number;;
    3
    6
    9
    12
    This is the end of the int list!
    - : unit = ()
    #
    

    【讨论】:

    • 啊对了!我现在知道我哪里出错了!我已经尝试将它输入到try.ocamlpro.com,就像我写它的方式一样,换行符就像我按下回车键一样。 (与您的编辑)最后的结果是......: - unit = () ....你知道它没有打印出三倍数字的列表吗?
    • let () = List.iter (printf "%d ") number ... 任何想法为什么在每个元素增加三倍后可能不会打印列表?
    • 它在 OCaml 顶层为我打印(当我修复它时)。你函数的结果确实是()(单位)。
    • 你的函数不会改变数字(你不能改变数字,列表是不可变的)。它只是打印出数字。我不知道您使用的在线系统,所以我无法评论为什么您不会得到输出。我会告诉你它对我来说是什么样的(上图)。
    • 太棒了!感谢您的解释和一切-对我的学习有很大帮助! :)
    【解决方案2】:

    请注意,实现您想要做的最优雅的方法是使用List.iter。它将给定函数(返回unit)应用于List 的每个元素。

    let print_triples = List.iter (fun x ->
      print_endline (string_of_int (3*x))
    );;
    
    val print_triples : int list -> unit = <fun>  
    

    你来了:

    # print_triples [1;2;3;4;5];;
    
    3
    6
    9
    12
    15
    - : unit = ()
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 2016-08-16
      • 1970-01-01
      相关资源
      最近更新 更多