Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing basic haskell function, taking Int x and doing function on [1..x]

I'm practicing some haskell, and having issues with something very basic in other languages.

I want my function to take an int and return a string

oddOnly :: Int -> String

and i want to print the output of that function

print (oddOnly 20)

I want this function to print all odd numbers from 1-20 for example

"1 3 5 7 9 11 13 15 17 19"

My function is only printing the final number obviously because i'm not iterating over a list of these numbers. How do I do that?

oddOnly x
    | x < 0 = error "neg"
    | x == 0 = "0"
    | mod x 2 /= 0 = show x
like image 696
Eddie Avatar asked Jul 20 '26 19:07

Eddie


1 Answers

I think you make things too complicated here. You can use filter :: (a -> Bool) -> [a] -> [a] here to filter a list, and use odd :: Integral i => i as filter condition:

oddOnly :: Integral i => i -> [i]
oddOnly n = filter odd [1..n]

or as a string:

import Data.List(intercalate)

oddOnly :: (Show i, Integral i) => i -> String
oddOnly n = intercalate " " (map show (filter odd [1..n]))

For example:

Prelude Data.List> putStrLn (oddOnly 15)
1 3 5 7 9 11 13 15

I'm not iterating over a list of these numbers. How do I do that?

Haskell's "workhorse" is recursion: you do not use for loops, etc. but you recurse on a list. You make recursive calls where you make a call with an different value, etc.

like image 80
Willem Van Onsem Avatar answered Jul 23 '26 16:07

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!