I'm trying to store function's result data in list but don't know how to define in the code.
I think the problem is 10th line.
| tst x == True = [x,xs..]
How could I define list where I will store the result data of tst x?
So, the expected output is below.
Main> two_sear evn [2,4,5,8]
[2,4,8]
Main> two_sear big [101]
[101]
My current approach:
evn :: Int -> Bool
evn x = mod x 2 == 0
big :: Int -> Bool
big x = x > 100
two_sear::(Int -> Bool) -> [Int] -> [Int]
two_sear tst [] = []
two_sear tst (x:xs)
| tst x == True = [x,xs..]
| otherwise = two_sear tst xs
It looks like you want to use a filter :: (a -> Bool) -> a -> a
here. So instead of using your own two_sear
, you can use filter instead.
For example:
Prelude> filter evn [2,4,5,8]
[2,4,8]
Prelude> filter big [101]
[101]
You can implement filter
yourself through recursion:
filter' :: (a -> Bool) -> [a] -> [a]
filter' p = go
where go [] = []
go (x:xs) | p x = x : go xs
| otherwise = go xs
We thus construct a list with (x : go xs)
, or less verbose x : go xs
. This is a "cons" with x
the head of the list, and we recurse with go xs
on the remaining items of the list.
The go
function can be implemented as a foldr
with:
import Data.Bool(bool)
filter' :: (a -> Bool) -> [a] -> [a]
filter' p = foldr ((bool id . (:)) <*> p) []
The Prelude
already has an implementation for even :: Integral i => i -> Bool
and you can define big
as:
big :: (Num n, Ord n) => n -> Bool
big = (<) 100
or:
big :: (Num n, Ord n) => n -> Bool
big = (100 <)