开发者

How to use filter like if then else statement on a list?

开发者 https://www.devze.com 2023-02-26 12:02 出处:网络
i would like to add 1 items to a list which has only one item and add items(after using toInt to convert to integer) in a list y if number of items greater than 1 and the last items are the same

i would like to add 1 items to a list which has only one item and add items(after using toInt to convert to integer) in a list y if number of items greater than 1 and the last items are the same

How to do?

import Data.List.Split

z = splitOn "+" "x^2+2*x^3+x^2"

y = map (splitOn "*") z

x = map head y

toInt :: [String] -> [Int]
toInt = map read

u = filter ((map length y)>1) y

Couldn't match expected type `a0 -> Bool' with actual type `Bool'
In the first argument of `filter', namel开发者_JAVA技巧y `((map length y) > 1)'
In the expression: filter ((map length y) > 1) y
In an equation for `u': u = filter ((map length y) > 1) y

Failed, modules loaded: none.


Your definition of u is obviously bad. It helps if you give type signatures, so we understand a little better what you are trying to do (even when you don't tell us in words).

You commented that you want all lists of length > 1, this is the same as getting all non-null lists after dropping the first element. So use filter, which tests each element separately (so you don't need map), and build a function that either tests a single list for length > 1 or it's sublist for null:

-- Use the O(n) length for your filter
u = filter ((> 1) . length) y

-- Or use an O(1) drop + null test
u' = filter (not . null . drop 1) y

Without using function composition (.) these functions are:

u = filter (\sublist -> length (sublist) > 1) y

u' = filter (\sublist -> not (null (drop 1 sublist))) y


The compiler is telling you that map length y > 1 is a boolean value, but filter wants a function there. I am not sure what you really want do to with y, please specify what you expect for different values of y.

0

精彩评论

暂无评论...
验证码 换一张
取 消