2

function が list の要素の大部分を満たし、 false が満たさない場合に True を返すコードを作成する必要があります。例:moreThan odd [1,2,3]は ですがTruemoreThan odd [1,2,3,4]ですFalse。これが私のコードです:

moreThan funkt xs
   = let
      control funkt n (x : xs)
         = control (if .?. then n + 1 else n) xs
      contol funkt _
         = False
   in
   control funtk 0 xs

誰かがそれを制御する方法と、何を書くべきかを教えてもらえますか.?. ありがとう!

4

5 に答える 5

3

リストが終了すると必ず戻るため、作成した関数はFalseすべての引数に対して返されます。False

作成する関数は、処理される要素の数と述語が真である要素の数の2つの変数を追跡する必要があります。このコードはおそらく宿題なので、関数の記述に使用できる構造を提供します。場所であなた自身のコードを記入してください-- ???

moreThan :: (a -> Bool) -> [a] -> Bool
moreThan pred = go 0 0 where
  -- procd: number of elements processed
  -- holds: number of elements for which pred holds
  go procd holds (x:xs) = go procd' holds' xs where
     procd' = -- ???
     holds' = -- ???
  go procd holds []     = -- ???

さらにヒントが必要な場合は、コメントを残してください。


この関数を書くためのより慣用的な方法は、foldを使用することです。

moreThan pred = finalize . foldr go (0,0) where
  -- process one element of the input, produce another tuple
  go (procd,holds) x = -- ???
  -- produce a boolean value from the result-tuple
  finalize (procd,holds) = -- ???
于 2012-05-21T21:43:42.567 に答える
2

あなたのライブラリを知ってください!

import Data.List(partition)
import Data.Function(on)

moreThan f = (uncurry $ on (>) length) . partition f

パーティションの使用が許可されていない場合は、自分で書きます:

part f xs = (filter f xs, filter (not.f) xs)

または、数値の方法に進みます。

moreThan f xs = 2*s > length xs where s = sum $ map (fromEnum.f) xs
于 2012-05-22T06:27:14.230 に答える
1

おそらく最も効率的な解決策ではありませんが、確かに非常に明確な解決策は次のとおりです。

moreThan :: (a -> Bool) -> [a] -> Bool
moreThan f xs = length ts > length fs where
    ts = filter id bools
    fs = filter not bools
    bools = map f xs
于 2012-05-21T23:22:15.187 に答える
1
majority :: (a -> Bool) -> [a] -> Bool
majority p = (0 <) . sum . map (\x -> if pred x then 1 else -1)

これは、リスト要素に対するマップ (pred x の場合は 1、そうでない場合は -1) であり、リスト要素を合計し、結果が > 0 であるかどうかを調べます。

于 2012-05-22T19:04:39.040 に答える
0

これが効率的であることを願っています (リストを 1 回だけトラバースします) が、それでもかなり明確です。

majority :: (a -> Bool) -> [a] -> Bool
majority pred = g . sum . map f
  where f x | pred x    = 1
            | otherwise = -1
        g y = 0 < y
于 2012-05-22T08:51:58.550 に答える