我不知道空元组来自哪里? 由于索引太大,我看不到结果的内容
如何删除空元组以使其过滤以打印出所有真实结果?
错误:
*主>设bb = filter(\ n - > snd n == True)alltrees1
:74:39:
无法匹配预期类型(a0, Bool)' with actual type
()'
预期类型:[(a0,Bool)]
实际类型:[()]
在filter', namely
alltrees1'的第二个论点中
在表达式中:filter(\ n - > snd n == True)alltrees1
运行:
:l trees.hs
let allparams = replicateM 3 [1.0, 2.0]
let alltrees = [getAllTrees c | x <- allparams, c <- [x]]
eval(alltrees!!1!!1) == eval(alltrees!!1!!1)
let alltrees1 = forM_ [0..(sizeoflist alltrees)] $ \i -> forM_ [0..(sizeoflist (alltrees!!i))] $ \j -> [(alltrees!!i!!j, eval(alltrees!!i!!j) == eval(alltrees!!i!!j))]
let bb = filter (\n -> if n != () then snd n == True) alltrees1
Haskell中:
import Data.List
import Control.Monad
import Math.Combinat
import System.IO
data Operation
= And
| Or
| MA
| MB
| Impl
deriving Show
data Mree x
= Meaf x
| Mode (Mree x) Operation (Mree x)
deriving Show
splits :: [a] -> [([a], [a])]
splits xs = zip (inits xs) (tails xs)
getAllTrees :: [a] -> [Mree a]
getAllTrees [] = []
getAllTrees [x] = return $ Meaf x
getAllTrees xs = do
(left, right) <- splits xs
guard $ not (null left) && not (null right)
leftT <- getAllTrees left
rightT <- getAllTrees right
op <- [And, Or]
return $ Mode leftT op rightT
eval :: Mree Double -> Double
eval (Meaf x) = x
eval (Mode l And r) = eval l
eval (Mode l Or r) = eval r
sizeoflist :: [a] -> Int
sizeoflist = length
答案 0 :(得分:1)
请注意,altrees1
的类型为[()]
。通过使用forM_
,您将丢弃内部计算的结果。
请注意,altrees
的类型为[ [ Mree Double ] ]
。
也许这就是你想要的:
allexprs :: [ Mree Double ]
allexprs = concat alltrees -- a list of all the Mrees in alters
alltrees2 = [ (x, eval x == eval x) | x <- allexprs ]
-- this is apparently what alltrees1 is doing
bb = [ x | (x, True) <- alltrees2 ]
-- same as: filter (\(x,b) -> b == True) altrees2
-- filter (\(x,b) -> b) alltrees2
-- filter (\xb -> snd xb) alltrees2
答案 1 :(得分:0)
基本的haskell List(和大多数集合)不会让你在同一个列表中存储空元组和非空元组,因为它们是不同的类型 - 所以,在这种情况下,说它没有意义
\n -> if n != () then snd n == True
现在:为什么列表中包含空元组列表?由于forM_的类型(通过hoogle找到):
forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()
在上面的上下文中(迭代列表,生成列表),具体如下:
forM_ :: [a] -> (a -> [b]) -> [()]
forM_的返回值(并且,作为命名约定,许多以下划线结尾的函数,如traverse_,for_和sequenceA_)是“无用的”;这些函数通常用于在某些monad中执行副作用,如IO。
注意:既然你没有使用那些索引来访问每个列表成员,那么使用map会更简洁:
map (map (\x -> (x, eval x == eval x))) allTrees
有关列表的详细信息,请参阅the chapter from the book learn you a haskell。