我需要创建依赖于插入列表和计数的布尔列表的代码。例如,当用户提供列表[0,1,2,3,4,5,6,7,8,9,10] 和计数= 2 时然后代码使布尔列表[true,false,true,false,true,false,true,false,true,false,true]
当 count = 3 时,它会使布尔列表[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
答案 0 :(得分:3)
使用高阶函数(推荐):
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
答案 1 :(得分:1)
喜欢这个吗?
let Group l c = [ for l' in 0..l -> (l' % c) = 0 ]
签名是Group : int -> int -> bool list
// H