2012-01-19 52 views
1

我需要代碼,它創建依賴於插入列表和計數的布爾列表。例如,當用戶給出列表[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]如何創建布爾列表的布爾值取決於插入計數和列表f#

計數= 3然後它將使布爾列表[真,假FALSE,TRUE,FALSE,FALSE,真,假FALSE,TRUE,FALSE]

如果計數= 4然後[TRUE,FALSE,FALSE,FALSE,TRUE,FALSE,FALSE,FALSE,TRUE,假]等等......

我寫了下面的代碼,但我認爲,這段代碼是錯誤的,我是新來的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

擴大你的問題說這可能是值得*爲什麼*你想要這樣做。你已經得到了一些有效的答案,但是通過給出一些上下文,你可能會得到一些建議來避免這個(相當奇怪的)構造。 – Kit

回答

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 
+0

注意:您的解決方案假設他想調整列表中的索引,而不是調整值。根據他的例子列表,這*可能*是他想要的,但我認爲這是值得指出的,在他被打倒之前...... :) – Benjol

1

是這樣的?

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

的signatue是Group : int -> int -> bool list

  • [a..b]創建整數從A到B(包括兩端)的列表
  • [用於a..b X - >˚F (x)]不變,但是將f應用於每個元素。
  • (a%c)= 0只是檢查a是否是模數c。

// H

+0

這兩種解決方案都很棒,感謝您的反饋人員:-) –