Haskell : Check for an exact substring [closed] - haskell

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to write a function which will check for an EXACT substring in the given string.
All I am using right now is isInfixOf but my friend just pointed out that it doesn't check for an EXACT word.
Example, if I am writing
`"hi " `isInfixOf` "hi you"`
then this will return True. But I don't want that. All I want is it should return True only if it contains "hi " i.e. exactly one space. How can I do that?

It seems like you are looking for a somewhat modified version of isInfixOf:
import Data.Maybe
import Data.List
isInfixOf' :: String -> String -> Bool
isInfixOf' xs ys = any p [stripPrefix xs zs | zs <- tails ys]
where
p Nothing = False
p (Just (' ' : _)) = False
p _ = True
The idea is that we first collect all strings that follow a matching substring and then test whether or not they start with a space.
For example:
> "hi " `isInfixOf'` "hi you"
False
> "hi " `isInfixOf'` "hi you"
True

Related

Haskell: a for loop for a REPL [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I am trying to write a something like a repl in Haskell and I want to replicate this code in C:
for (int c = getc(stdin); c != 'e'; c = getc(stdin)) {
printf("I got %c!\n", c);
}
I could use recursion but I am afraid of exeeding the limit.
You should use recursion. Haskell is designed to handle recursion without limits, and recursion can and should be used even for effectively infinite loops (e.g., event processing loops or REPL loops).
So, you could more or less write your program as follows:
main = do
txt <- getLine
if txt /= "exit" then do
putStrLn $ "I got " ++ txt ++ "!"
main
else do
return ()
giving:
$ ./repl
foo
I got foo!
bar
I got bar!
exit
$
I've written it to grab a whole line of input instead of single character, since there are typically issues with buffered input when trying to grab input character by character. This infinite recursion works fine and will not exceed any limit no matter how many billions of lines it processes before exiting.
In most real-world programs, you don't want the whole main program to loop, so you typically write something like the following. Here, I've used when which is a nicer looking way of writing the pattern if xxx then yyy else return ().
import Control.Monad -- for definition of "when"
main = do
-- initialization
putStrLn $ "Welcome to my REPL!"
-- start the main loop
loop
-- clean up
putStrLn $ "Thanks so much for using my REPL!"
-- definition of main loop
loop = do
txt <- getLine
when (txt /= "exit") $ do
putStrLn $ "I got " ++ txt ++ "!"
loop

If length is 2 do Haskell [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm new to Haskell and I'm not sure how to work around the If-Else, for example:
function str = if ((length str) = 2) then (....)
In java we would:
if (str.length =2){
str = "2"}
else { str ="1"}
How do you write it in haskell?
You can use Guards:
fnc :: String -> String
fnc s | length s == 2 = ...
| otherwise = ...
More to Guards
Or conditions
fnc :: String -> String
fnc s = if length s == 2 then ... else ...
It is also possible to use pattern matching, more here.
There are several ways to achieve conditions (e.g. case of) in Haskell.

How to interpolate a string in Haskell? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a bunch of strings stored in a config file. The strings contain values that must be evaluated at runtime:
"aaa #{val1} bbb"
"ccc #{val235} ddd"
How can I replace the #{valN} at runtime using the standard, out of the box, Haskell library? Do string interpolations, that is.
I can change the format of parts that have to be interpolated, if Haskell requires so. Namely, instead of #{valN} I could use ${valN} or anything else.
As far as I know, there are three ways to do what you want:
1. (++) operator
Since String is just a list of Char, so you can use (++) operator to combine many strings:
> "aaa " ++ show (val1) ++ " bbb"
> "ccc " ++ show (val235) ++ " ddd"
2. printf
printf can really return String type:
λ> printf "Hi, %s!" "Bob" :: String
"Hi, Bob!"
λ> :t it
it :: String
So all you need to do is giving a explicit type signature to your function which you need to return String.
3. string-interpolate package
The following is the sample code from the package document
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
import Data.Text
import Data.String.Interpolate ( i )
λ> age = 33 :: Int
λ> name = "Tatiana" :: Text
λ> [i|{"name": "#{name}", "age": #{age}}|] :: String
>>> "{\"name\": \"Tatiana\", \"age\": 33}"
λ> [i|
Name: #{name}
Age: #{age}
|] :: String
>>> "\nName: Tatiana\nAge: 33\n"
Of course, there are some other interpolation libraries, which are also listed in the package pages.
An option not mentioned in the comments or in Z-Y.L's answer is typelits-printf:
ghci> putStrLn $ printf #"You have %.2f dollars, %s" 3.62 "Luigi"
You have 3.62 dollars, Luigi
See more examples on https://github.com/mstksg/typelits-printf

How to find time complexity of this program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a data list.
db = [("Ada","works", "IBM")
,("Alice","director", "Ada")
,("Tom","works", "IBM")
,("Tommy","director", "Tom")
,("IBM","isat", "CA")
,("CA","in", "USA")
]
ask db = map (\(x,y,z) -> (z == "IBM")) db
How to calculate the complexity of O(n)?
If I want to get the result by the length of list 2,5,10.O(n) is same like 2,5,10?And If I do
trans2 db = concat (map ((x,y,z) -> concat (map((x',y',z') -> if (z==x') then [] else [(x,y ++ "." ++ y',z')] else []) db)) db )
How can I calculate the O(n)? The runtime of program? The timming complexity
The question is unclear and I expect it will soon be closed. Briefly.
O(n) is a complexity. If you know O(n) and you wanted complexity then you're done.
The length of the list (2, 5, 10, what have you) is not a factor in the complexity in this case since the length is what the n is representing.
There is no code that will calculate the complexity of the algorithm automatically. It is a manual analysis.

Filter a haskell data type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is my code I have so far:
arcticMonkeysAreTheBest = Review "Arctic Monkeys"
5
arcticMonkeys2012
"18/08/2013"
"België"
Festival
["I bet you look good on the dancefloor", "When the sun goes down", "Still take you home"]
arcticMonkeysRock = Review "Artic Monkeys"
5
arcticMonkeys2013
"17/08/2013"
"België"
Zaal
["R U Mine?", "Arabella", "Why'd you only call me when you're high?"]
reviews = [arcticMonkeysAreTheBest, arcticMonkeysRock]
Now my question is: How can I filter the reviews with Location = Zaal for example?
Is it also possible to filter with two criteria? For example where artist= Arctic Monkeys and where Location = Zaal?
I would probably define your review type to be
data Review = Review
{ reviewBand :: String
, reviewStars :: Integer
, reviewTour :: Tour
, reviewData :: String
, reviewCountry :: String
, reviewLocation :: Location
, reviewSongs :: [String]
} deriving (Eq,Ord,Show)
and your Location type to be
data Location = Festival | Zaal deriving (Eq,Ord,Show)
You can then easily do
>> filter (\review -> reviewLocation review == Zaal) reviews
or even more concisely
>> filter ((== Zaal) . reviewLocation) reviews
Edit
If you want this as a function, it is as simple as defining
filterByLocation :: Location -> [Review] -> [Review]
filterByLocation location = filter (\r -> reviewLocation r == location)
Assuming your Review type is defined like
data Review = Review String Int String String String String [String]
then you can write a function to match a Review based on a given location:
findByLocation loc (Review _ _ _ _ _ location _) | loc == location = True
findByLocation _ _ = False
Then you can find reviews with the location Zaal with
let matches = filter (findByLocation Zaal) reviews

Resources