Sep 20, 2010

Haskell - filter

Filter
If a list meet a certain condition it will
create another list according to that. Try this,
retainEven :: [Int]->[Int]
retainEven []=[]
retainEven (n:ns)=
if (mod n 2 == 0)
then n:(retainEven ns)
else retainEven ns

If you run this program like

retainEven [12,13,14,15,16]
You will get the output as;
[12,14,16]

If then else statment with strings

msg :: Int -> String
msg n =
if n< 10 then "Less than 10" else "Equal or greater than 10" Let and where addStr :: Float -> String -> Float
addStr xstr = x + read str
sumStr :: [String] -> Float
SumStr = foldl addstr 0.0

But You can write this by using let keyword easilly.
sumStr=
let addStr x str = x + read str
in foldl addStr 0.0

or else you can write it by using where keyword like this.
aumStr = foldl addStr 0.0
where addStr x str = x + read str

No comments:

Post a Comment

Your comments are always welcome ...