如何创建布尔值的布尔值列表取决于f中插入的计数和列表



我需要根据插入的列表和计数创建布尔列表的代码。例如,当用户给出List[0,1,2,3,4,5,6,7,8,9,10]计数=2时,则代码生成boolList[true,false,true,false,true,false

计数=3时,它将生成布尔列表[true,false,false,true,false,true,false]

如果计数=4,则[真、假、假、真、假,假、假,真、假]依此类推…

我已经写了以下代码,但我认为,这个代码是错误的,我是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

使用高阶函数(推荐):

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

这样?

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

标志为Group : int -> int -> bool list

  • [a.b]创建一个从a到b(包括a和b)的整数列表
  • [对于a..b->f(x)中的x]也做同样的操作,但将f应用于每个元素
  • (a%c)=0只是检查a是否为模量c

//H

最新更新