Reputation: 93
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
Upvotes: 2
Views: 404
Reputation: 16224
Just in addition to the already good answer here. Functions in Haskell are like any other value, and also your current functions can be curried (indeed every function in Haskell is curried). Said that, here an example:
fs = [(+), (*), (-), (div)]
ints = [(2,4), (5,3), (6,2), (9,3)]
applyFs :: [a -> b -> c] -> [(a, b)] -> [c]
applyFs fs ns = zipWith (($) . uncurry) fs ns
=> [6,15,4,3]
As you can see, fs
is a list a function, completely valid
Upvotes: 1
Reputation: 476709
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 <)
Upvotes: 2