【问题标题】:Find common chars in 2 list Ocaml在 2 个列表 Ocaml 中查找常见字符
【发布时间】:2017-04-25 05:31:09
【问题描述】:

我是 Ocaml 的新手,我的问题是: 我有 2 个字符列表。我想将两个列表的常见字符放入另一个列表(错误。我的基本代码是这样的(“检查 ->hd1

let rec check list1 list2 = match list1, list2 with
| hd1::tl1, hd2::tl2 when hd1 = hd2 -> hd1
| hd1::tl1, hd2::tl2 ->  check  hd1 tl2
| [],[] -> ' '
| _::_,_ -> ' '
| [],_::_ -> ' ';;

check ['l'; 'e'; 'l'; 'l'; 'o'] ['h'; 'e'; 'o'];;

我最大的问题是如何修复一个列表并继续另一个?

另一个问题是当我找到一个字符时删除它。 (例如:list1="hello" list2="helo" 找到第一个“l”时,list2="heo" final_list-->"helo")。

我必须更好地学习这个模式的概念。

【问题讨论】:

    标签: list char ocaml matching


    【解决方案1】:
    let check l1 l2 =
     List.fold_left ( fun linter e1 ->
      if(List.exists((=)e1)l2) then e1::linter else linter
     ) [] l1;;
    

    测试

    # check ['l'; 'e'; 'l'; 'l'; 'o'] ['h'; 'e'; 'o'];;
    - : char list = ['o'; 'e']
    

    一些解释

    List.exists :检查 e1 是否在 l2 中

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 2020-02-23
      • 2019-04-25
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      相关资源
      最近更新 更多