如何在OCaml中使用List.map [英] How to use List.map in OCaml

查看:381
本文介绍了如何在OCaml中使用List.map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在OCaml中有一个列表列表,返回了[[7; 5]; [7; 3; 2]].我知道OCaml中有很多List函数.我想在每个值之间打印一个加号,就像在Python或Ruby中那样.在Python中,我使用print('+'.join(map(str,lst)))进行此操作,其中lst是列表,str是要转换为字符串.如何在OCaml中做到这一点?

I have a list of lists in OCaml returning [[7; 5]; [7; 3; 2]]. I know there's a lot of List functions in OCaml. I want to print each value out with a plus sign between them like one would do in Python or Ruby. In Python, I do this with print('+'.join(map(str,lst))) where lst is the list, str is to convert to a string. How do I do this in OCaml?

控制台输入

int list list = [[7; 5]; [7; 3; 2]]

控制台输出

7 + 5
7 + 3 + 2

更新

let main num = 
    print_string "Prime Partitions Program" in
    print_linked_list (prime_part num (all_primes 2 num)) ;;

我有一个包装器功能main.它调用所有3个功能使所有功能正常工作.但是,解释器给了我一个未绑定的值num. prime_part是一种将链接列表退回的功能,如控制台输入所示. all_primes是用作prime_part的输入的功能.如何让这些函数作为print_linked_list函数的输入?

I have a wrapper function main. It calls all 3 functions for everything to work. However, the interpreter is giving me an unbound value num. prime_part is a function that gives the linked list back as shown in the console input. all_primes is a function that serves as input to prime_part. How can I make these functions feed as input to the print_linked_list function?

推荐答案

以下是一个打印带有加号的int list list的函数:

Here's a function that prints an int list list with plus signs:

let pll ll =
    let pl l =
        print_endline (String.concat " + " (List.map string_of_int l))
    in
    List.iter pl ll

这是您的示例的外观:

val pll : int list list -> unit = <fun>
# pll [[7; 5]; [7; 3; 2]];;
7 + 5
7 + 3 + 2
- : unit = ()

这篇关于如何在OCaml中使用List.map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆