[Haskell-beginners] How do I use Guards in record syntax?
Gesh
gesh at gesh.uni.cx
Mon Apr 14 15:04:50 UTC 2014
On April 14, 2014 9:03:20 AM GMT+03:00, Dimitri DeFigueiredo <defigueiredo at ucdavis.edu> wrote:
>
>I'm having some trouble understanding where I can or cannot use guards
>inside record syntax. I'm writing a simple conversion routine, but I am
>
>not able to write it without inserting an extra let. Do I need a let
>expression here? Am I missing something?
>
>--------------
>data OldTrade = OldTrade {
> oldprice :: Double ,
> oldamount :: Double ,
> oldbuysell :: String -- "buy", "sell" or ""
> } deriving( Eq, Show)
>
>
>data BuyOrSell = Buy | Sell | Unknown deriving(Eq, Show)
>
>data Trade = Trade {
> price :: Double ,
> amount :: Double ,
> buysell :: BuyOrSell
> } deriving( Eq, Show)
>
>convert :: OldTrade -> Trade
>
>convert ot = Trade { price = oldprice ot,
> amount = oldamount ot,
> buysell = let x | oldbuysell ot == "buy" = Buy
> | oldbuysell ot == "sell" = Sell
> | otherwise = Unknown
> in x
> }
>
>-- how do I eliminate the 'let' expression here?
>-- I wanted to write something like:
>--
>-- buysell | oldbuysell ot == "buy" = Buy
>-- | oldbuysell ot == "sell" = Sell
>-- | otherwise = Unknown
>
>--------------
>
>Thanks!
>
>Dimitri
>
>
>
>
>_______________________________________________
>Beginners mailing list
>Beginners at haskell.org
>http://www.haskell.org/mailman/listinfo/beginners
Note that this has nothing to do with record syntax specifically. Rather, what you're asking is how to write a multi-way if expression. Your way is to introduce a local binding using a let statement, which allows you to use pattern guards as you did.
Usually, bowever, you'd use a case statement to avoid the binding. However, you could use the MultiWayIf LANGUAGE pragma, as suggested elsewhere in this thread. Or you could float out the binding to a where clause, except that doesn't seem to be what you're looking for.
Hoping to help,
Gesh
More information about the Beginners
mailing list