[Haskell-beginners] Add parenthesis to Sin/Cos expressions

Sumit Sahrawat, Maths & Computing, IIT (BHU) sumit.sahrawat.apm13 at iitbhu.ac.in
Thu Nov 5 17:16:43 UTC 2015


The spirit of declarative programming lies in the fact that you try to just
tell the compiler what something means. Instead of thinking about keeping
track of the numbers of parentheses, and then applying them afterwards, I
would suggest you create a function to do the same job:

    bracketed :: String -> String
    bracketed s = "(" ++ s ++ ")"

This would allow you to remove the numeric argument, and also write cleaner
code.

The second thing that you can improve is the pattern matching. You can use
isPrefixOf
<http://hackage.haskell.org/package/base-4.8.1.0/docs/Data-List.html#v:isPrefixOf>
to
check functions, or use a take inside a case statement to get cleaner
handling of different cases.

    case take 3 str of
      "sin" -> ...
      "cos" -> ...
       _ -> ...

This would also let you debug your code more easily, just as you require.

On 4 November 2015 at 14:51, Imants Cekusins <imantc at gmail.com> wrote:

> > a function that is supposed to add parenthesis to sin/cos expressions.
> a) Sin 5 + 3        ->    Sin(5) + 3
> b) Sin Cos (5+3)   ->    Sin (Cos(5+3))
> c) Sin Cos 5 * 3   ->    Sin(Cos(5)) * 3
>
> are you looking for textual representation or actual Haskell code which
> runs?
> if actual code, these examples may be re-written like this:
> a) sin 5 + 3
> b) sin $ cos $ 5 + 3
> c) sin (cos 5) * 3
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>



-- 
Regards

Sumit Sahrawat
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20151105/a5795810/attachment.html>


More information about the Beginners mailing list