【问题标题】:How to create boolean list of boolean depended on inserted count and list in f#如何根据插入的计数和 f# 中的列表创建布尔值列表
【发布时间】:2012-02-14 02:54:59
【问题描述】:

我需要根据插入的列表和计数创建布尔列表的代码。例如,当用户给出 List[0,1,2,3,4,5,6,7,8,9,10]count=2 那么然后代码使 bool List [true,false,true,false,true,false,true,false,true,false,true]

count = 3bool List [true, false, false, true, false, false, true, false, false, true, false]

如果 count = 4 那么 [true, false, false, false, true, false, false, false, true, false] 以此类推....

我已经编写了以下代码,但我认为这段代码是错误的,我是 f# 的新手,所以我需要你的帮助。谢谢。

   let Group (s1 : List) (c : int) =
        let lenght = List.length(s1)
        (lenght)
           let rec MakeBool (count : int) (boolist : List) =
                while lenght > 0 do
                    if lenght % count = 0 then boolist = true::boolist 
                    if lenght % count <> 0 then boolist = false::boolist    
                    lenght = lenght - 1
                    MakeBool count boolist

【问题讨论】:

  • 可能值得扩展您的问题,说出您想要这样做的为什么。你已经得到了一些有效的答案,但是通过提供一些上下文,你可能会得到一些避免这种(相当奇怪的)结构的建议。

标签: list f# count boolean


【解决方案1】:

使用高阶函数(推荐):

let group ls c = 
    ls |> List.mapi (fun i _ -> i%c = 0)

滚动你自己的函数:

let group ls c =
 let length = List.length ls    
 let rec makeBool count acc =
  if count = length then acc // Come to the end of ls, return the accummulator
  elif count%c=0 then // Satisfy the condition, prepend true to the accummulator
    makeBool (count+1) (true::acc)
  else  // Otherwise prepend false to the accummulator
    makeBool (count+1) (false::acc)
 List.rev (makeBool 0 []) // The accummulator is in backward order, reverse it

【讨论】:

  • 注意:您的解决方案假设他想要调整列表中的索引,而不是值。鉴于他的示例列表,可能是他想要的,但我认为值得指出,在他被标记之前...:)
【解决方案2】:

像这样?

let Group l c =  [ for l' in  0..l  -> (l' % c) = 0 ] 

签名是Group : int -&gt; int -&gt; bool list

  • [ a..b ] 创建一个从 a 到 b 的整数列表(包括两者)
  • [ for x in a..b -> f (x) ] 的作用相同,但将 f 应用于每个元素。
  • (a % c) = 0 只检查 a 是否为模数 c。

//H

【讨论】:

  • 两种解决方案都很棒,谢谢你们的反馈:-)
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 2013-09-11
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 2023-02-14
  • 2021-08-30
相关资源
最近更新 更多