How would I find the distance between two elements in a list?Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)Getting started with HaskellBasic Structure of a Haskell ProgramCheck if two lists have the same elementsHow to find the node that holds the minimum element in a binary tree in Haskell?How to optimize filtering of a listChecking if two lists are equal at Nth positionIntuitively, how does Haskell find the length of a list without using a standard length function?Haskell mix two listsGap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)Testing if one list is a sublist of another without testing equality between elements
How to evolve human-like eyes that can stare at the sun without protection?
Is anyone advocating the promotion of homosexuality in UK schools?
How can I calculate the sum of 2 random dice out of a 3d6 pool in AnyDice?
Why are they 'nude photos'?
Meaning of the negation in phrases like "не должен прочитать"
Are there any sports for which the world's best player is female?
Referring to different instances of the same character in time travel
What steps should I take to lawfully visit the United States as a tourist immediately after visiting on a B-1 visa?
How to md5 a list of filepaths contained in a file?
How is angular momentum conserved for the orbiting body if the centripetal force disappears?
RPI3B+: What are the four components below the HDMI connector called?
How to memorize multiple pieces?
What's the point of having a RAID 1 configuration over incremental backups to a secondary drive?
How were Martello towers supposed to work?
Why didn't Nick Fury expose the villain's identity and plans?
How to convert a file with several spaces into a tab-delimited file?
How did the hit man miss?
Is there any word for "disobedience to God"?
What explains 9 speed cassettes price differences?
Was I subtly told to resign?
Credit score and financing new car
How would my creatures handle groups without a strong concept of numbers?
Is a 10th-level Transmutation wizard considered a shapechanger for the purpose of effects such as Moonbeam?
During copyediting, journal disagrees about spelling of paper's main topic
How would I find the distance between two elements in a list?
Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)Getting started with HaskellBasic Structure of a Haskell ProgramCheck if two lists have the same elementsHow to find the node that holds the minimum element in a binary tree in Haskell?How to optimize filtering of a listChecking if two lists are equal at Nth positionIntuitively, how does Haskell find the length of a list without using a standard length function?Haskell mix two listsGap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)Testing if one list is a sublist of another without testing equality between elements
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have to find the distance between first appearance of two elements in a list. The program we are using is Haskell. I've been online for HOURS trying to look for help on how to start or direction to solve it. Please help!
This is how we are defining it:gap :: (Eq a) => a -> a -> [a] -> Maybe Int
Here are some examples:
> gap 3 8 [1..10]
Just 5
> gap 8 3 [1..10]
Nothing
> gap 'h' 'l' "hello"
Just 2
> gap 'h' 'z' "hello"
Nothing
haskell
|
show 4 more comments
I have to find the distance between first appearance of two elements in a list. The program we are using is Haskell. I've been online for HOURS trying to look for help on how to start or direction to solve it. Please help!
This is how we are defining it:gap :: (Eq a) => a -> a -> [a] -> Maybe Int
Here are some examples:
> gap 3 8 [1..10]
Just 5
> gap 8 3 [1..10]
Nothing
> gap 'h' 'l' "hello"
Just 2
> gap 'h' 'z' "hello"
Nothing
haskell
2
have a look at theData.List
library hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html , there are many different approaches to problems like this that depend on how much you want/have to write your own functions from scratch
– Lorenzo
Mar 26 at 2:19
1
Also remember you can look for function by types on Hoogle hoogle.haskell.org, so in this case you would want a function that, given an element and a list, returns its index:a -> [a] -> Maybe Int
– Lorenzo
Mar 26 at 2:21
2
What wouldgap 'a' 'a' "a"
be?Just 0
orNothing
? How aboutgap 'a' 'a' "aa"
?Just 0
orJust 1
?
– Joseph Sible
Mar 26 at 2:25
2
Possible duplicate of Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)
– Joseph Sible
Mar 26 at 3:10
2
@AaditMShah, I would reach forelemIndex
for the second part.
– dfeuer
Mar 26 at 3:40
|
show 4 more comments
I have to find the distance between first appearance of two elements in a list. The program we are using is Haskell. I've been online for HOURS trying to look for help on how to start or direction to solve it. Please help!
This is how we are defining it:gap :: (Eq a) => a -> a -> [a] -> Maybe Int
Here are some examples:
> gap 3 8 [1..10]
Just 5
> gap 8 3 [1..10]
Nothing
> gap 'h' 'l' "hello"
Just 2
> gap 'h' 'z' "hello"
Nothing
haskell
I have to find the distance between first appearance of two elements in a list. The program we are using is Haskell. I've been online for HOURS trying to look for help on how to start or direction to solve it. Please help!
This is how we are defining it:gap :: (Eq a) => a -> a -> [a] -> Maybe Int
Here are some examples:
> gap 3 8 [1..10]
Just 5
> gap 8 3 [1..10]
Nothing
> gap 'h' 'l' "hello"
Just 2
> gap 'h' 'z' "hello"
Nothing
haskell
haskell
edited Mar 26 at 2:41
Alec
25.6k4 gold badges49 silver badges96 bronze badges
25.6k4 gold badges49 silver badges96 bronze badges
asked Mar 26 at 2:13
Lola MartinezLola Martinez
144 bronze badges
144 bronze badges
2
have a look at theData.List
library hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html , there are many different approaches to problems like this that depend on how much you want/have to write your own functions from scratch
– Lorenzo
Mar 26 at 2:19
1
Also remember you can look for function by types on Hoogle hoogle.haskell.org, so in this case you would want a function that, given an element and a list, returns its index:a -> [a] -> Maybe Int
– Lorenzo
Mar 26 at 2:21
2
What wouldgap 'a' 'a' "a"
be?Just 0
orNothing
? How aboutgap 'a' 'a' "aa"
?Just 0
orJust 1
?
– Joseph Sible
Mar 26 at 2:25
2
Possible duplicate of Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)
– Joseph Sible
Mar 26 at 3:10
2
@AaditMShah, I would reach forelemIndex
for the second part.
– dfeuer
Mar 26 at 3:40
|
show 4 more comments
2
have a look at theData.List
library hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html , there are many different approaches to problems like this that depend on how much you want/have to write your own functions from scratch
– Lorenzo
Mar 26 at 2:19
1
Also remember you can look for function by types on Hoogle hoogle.haskell.org, so in this case you would want a function that, given an element and a list, returns its index:a -> [a] -> Maybe Int
– Lorenzo
Mar 26 at 2:21
2
What wouldgap 'a' 'a' "a"
be?Just 0
orNothing
? How aboutgap 'a' 'a' "aa"
?Just 0
orJust 1
?
– Joseph Sible
Mar 26 at 2:25
2
Possible duplicate of Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)
– Joseph Sible
Mar 26 at 3:10
2
@AaditMShah, I would reach forelemIndex
for the second part.
– dfeuer
Mar 26 at 3:40
2
2
have a look at the
Data.List
library hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html , there are many different approaches to problems like this that depend on how much you want/have to write your own functions from scratch– Lorenzo
Mar 26 at 2:19
have a look at the
Data.List
library hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html , there are many different approaches to problems like this that depend on how much you want/have to write your own functions from scratch– Lorenzo
Mar 26 at 2:19
1
1
Also remember you can look for function by types on Hoogle hoogle.haskell.org, so in this case you would want a function that, given an element and a list, returns its index:
a -> [a] -> Maybe Int
– Lorenzo
Mar 26 at 2:21
Also remember you can look for function by types on Hoogle hoogle.haskell.org, so in this case you would want a function that, given an element and a list, returns its index:
a -> [a] -> Maybe Int
– Lorenzo
Mar 26 at 2:21
2
2
What would
gap 'a' 'a' "a"
be? Just 0
or Nothing
? How about gap 'a' 'a' "aa"
? Just 0
or Just 1
?– Joseph Sible
Mar 26 at 2:25
What would
gap 'a' 'a' "a"
be? Just 0
or Nothing
? How about gap 'a' 'a' "aa"
? Just 0
or Just 1
?– Joseph Sible
Mar 26 at 2:25
2
2
Possible duplicate of Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)
– Joseph Sible
Mar 26 at 3:10
Possible duplicate of Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)
– Joseph Sible
Mar 26 at 3:10
2
2
@AaditMShah, I would reach for
elemIndex
for the second part.– dfeuer
Mar 26 at 3:40
@AaditMShah, I would reach for
elemIndex
for the second part.– dfeuer
Mar 26 at 3:40
|
show 4 more comments
2 Answers
2
active
oldest
votes
An answer which is expected to run fast:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x y ls = elemIndex y $ dropWhile ((/=) x) ls
If you do not want to rely on Data.List
then you have to write and add your own elemIndex'
.
After Daniel Wagner's feedback an alternative:
gap' :: Eq a => a -> a -> [a] -> Maybe Int
gap' x y ls
| null ls' = Nothing
| head ls' == y = Nothing
| otherwise = elemIndex y ls'
where
ls' = dropWhile (t -> t /= x && t /= y) ls
Same comment as I gave dfeuer: this does not appear to comply to the spec. Consider e.g.gap 'a' 'b' "bacb"
-- this reportsJust 2
, which is clearly incorrect. (Nothing
,Just 1
, orJust (-1)
all might be sensible choices depending on exactly how you interpret the spec.)
– Daniel Wagner
Mar 26 at 11:46
@DanielWagner thanks, see update
– Elmex80s
Mar 26 at 12:37
Ah nice, upvoted!
– Daniel Wagner
Mar 26 at 13:41
Just 2 seems correct to me @Daniel . The second example case indicates that the second argument should appear in the list at or beyond the first argument. On "bacb" then gap 'a' 'a' is Just 0, gap 'a' 'c' is Just 1, gap 'a' 'b' is Just 2
– moonGoose
Mar 26 at 16:40
@ATayler The second example's return value is not aJust
, so I don't see how you can use it to support returning aJust
in some other case.
– Daniel Wagner
Mar 26 at 17:27
|
show 3 more comments
Here's how I'd do it:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x1 x2 xs = do
i <- elemIndex x1 xs
j <- elemIndex x2 xs
if i <= j
then Just (j - i)
else Nothing
Credits to dfeuer for reminding me of the elemIndex
function.
This is gratuitously inefficient.dropWhile
was the right way to start.
– dfeuer
Mar 26 at 5:24
1
@dfeuer I think it is about as efficient as can be done given the spec. If I have correctly guessed what you have in mind fordropWhile
, it will get the wrong answer forgap 'a' 'b' "bacb"
. (Whether the code in the answer gets it right or not is not clear -- the spec is a bit ambiguous, I have to say -- but thedropWhile
version will definitely get it wrong!)
– Daniel Wagner
Mar 26 at 5:27
@DanielWagner, it seems a bit ambiguous, but I see what you mean. However, it's still not the best way, because it traverses the list twice, retaining memory. You could use a slightly differentdropWhile
invocation, or to avoid a redundant test work up something custom.
– dfeuer
Mar 26 at 5:33
@dfeuer I agree. Without optimizations, this code is very inefficient. However, a smart compiler could most probably perform loop fusion to traverse the list only once. Either way, the first step is to get the program right, and the next step is to perform optimizations if necessary. If it doesn't matter that this code is inefficient, then let it be. However, if you find out that it's a performance bottleneck only then should you bother optimizing it.
– Aadit M Shah
Mar 26 at 11:08
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55348906%2fhow-would-i-find-the-distance-between-two-elements-in-a-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
An answer which is expected to run fast:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x y ls = elemIndex y $ dropWhile ((/=) x) ls
If you do not want to rely on Data.List
then you have to write and add your own elemIndex'
.
After Daniel Wagner's feedback an alternative:
gap' :: Eq a => a -> a -> [a] -> Maybe Int
gap' x y ls
| null ls' = Nothing
| head ls' == y = Nothing
| otherwise = elemIndex y ls'
where
ls' = dropWhile (t -> t /= x && t /= y) ls
Same comment as I gave dfeuer: this does not appear to comply to the spec. Consider e.g.gap 'a' 'b' "bacb"
-- this reportsJust 2
, which is clearly incorrect. (Nothing
,Just 1
, orJust (-1)
all might be sensible choices depending on exactly how you interpret the spec.)
– Daniel Wagner
Mar 26 at 11:46
@DanielWagner thanks, see update
– Elmex80s
Mar 26 at 12:37
Ah nice, upvoted!
– Daniel Wagner
Mar 26 at 13:41
Just 2 seems correct to me @Daniel . The second example case indicates that the second argument should appear in the list at or beyond the first argument. On "bacb" then gap 'a' 'a' is Just 0, gap 'a' 'c' is Just 1, gap 'a' 'b' is Just 2
– moonGoose
Mar 26 at 16:40
@ATayler The second example's return value is not aJust
, so I don't see how you can use it to support returning aJust
in some other case.
– Daniel Wagner
Mar 26 at 17:27
|
show 3 more comments
An answer which is expected to run fast:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x y ls = elemIndex y $ dropWhile ((/=) x) ls
If you do not want to rely on Data.List
then you have to write and add your own elemIndex'
.
After Daniel Wagner's feedback an alternative:
gap' :: Eq a => a -> a -> [a] -> Maybe Int
gap' x y ls
| null ls' = Nothing
| head ls' == y = Nothing
| otherwise = elemIndex y ls'
where
ls' = dropWhile (t -> t /= x && t /= y) ls
Same comment as I gave dfeuer: this does not appear to comply to the spec. Consider e.g.gap 'a' 'b' "bacb"
-- this reportsJust 2
, which is clearly incorrect. (Nothing
,Just 1
, orJust (-1)
all might be sensible choices depending on exactly how you interpret the spec.)
– Daniel Wagner
Mar 26 at 11:46
@DanielWagner thanks, see update
– Elmex80s
Mar 26 at 12:37
Ah nice, upvoted!
– Daniel Wagner
Mar 26 at 13:41
Just 2 seems correct to me @Daniel . The second example case indicates that the second argument should appear in the list at or beyond the first argument. On "bacb" then gap 'a' 'a' is Just 0, gap 'a' 'c' is Just 1, gap 'a' 'b' is Just 2
– moonGoose
Mar 26 at 16:40
@ATayler The second example's return value is not aJust
, so I don't see how you can use it to support returning aJust
in some other case.
– Daniel Wagner
Mar 26 at 17:27
|
show 3 more comments
An answer which is expected to run fast:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x y ls = elemIndex y $ dropWhile ((/=) x) ls
If you do not want to rely on Data.List
then you have to write and add your own elemIndex'
.
After Daniel Wagner's feedback an alternative:
gap' :: Eq a => a -> a -> [a] -> Maybe Int
gap' x y ls
| null ls' = Nothing
| head ls' == y = Nothing
| otherwise = elemIndex y ls'
where
ls' = dropWhile (t -> t /= x && t /= y) ls
An answer which is expected to run fast:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x y ls = elemIndex y $ dropWhile ((/=) x) ls
If you do not want to rely on Data.List
then you have to write and add your own elemIndex'
.
After Daniel Wagner's feedback an alternative:
gap' :: Eq a => a -> a -> [a] -> Maybe Int
gap' x y ls
| null ls' = Nothing
| head ls' == y = Nothing
| otherwise = elemIndex y ls'
where
ls' = dropWhile (t -> t /= x && t /= y) ls
edited Mar 26 at 12:35
answered Mar 26 at 9:41
Elmex80sElmex80s
2,3801 gold badge8 silver badges16 bronze badges
2,3801 gold badge8 silver badges16 bronze badges
Same comment as I gave dfeuer: this does not appear to comply to the spec. Consider e.g.gap 'a' 'b' "bacb"
-- this reportsJust 2
, which is clearly incorrect. (Nothing
,Just 1
, orJust (-1)
all might be sensible choices depending on exactly how you interpret the spec.)
– Daniel Wagner
Mar 26 at 11:46
@DanielWagner thanks, see update
– Elmex80s
Mar 26 at 12:37
Ah nice, upvoted!
– Daniel Wagner
Mar 26 at 13:41
Just 2 seems correct to me @Daniel . The second example case indicates that the second argument should appear in the list at or beyond the first argument. On "bacb" then gap 'a' 'a' is Just 0, gap 'a' 'c' is Just 1, gap 'a' 'b' is Just 2
– moonGoose
Mar 26 at 16:40
@ATayler The second example's return value is not aJust
, so I don't see how you can use it to support returning aJust
in some other case.
– Daniel Wagner
Mar 26 at 17:27
|
show 3 more comments
Same comment as I gave dfeuer: this does not appear to comply to the spec. Consider e.g.gap 'a' 'b' "bacb"
-- this reportsJust 2
, which is clearly incorrect. (Nothing
,Just 1
, orJust (-1)
all might be sensible choices depending on exactly how you interpret the spec.)
– Daniel Wagner
Mar 26 at 11:46
@DanielWagner thanks, see update
– Elmex80s
Mar 26 at 12:37
Ah nice, upvoted!
– Daniel Wagner
Mar 26 at 13:41
Just 2 seems correct to me @Daniel . The second example case indicates that the second argument should appear in the list at or beyond the first argument. On "bacb" then gap 'a' 'a' is Just 0, gap 'a' 'c' is Just 1, gap 'a' 'b' is Just 2
– moonGoose
Mar 26 at 16:40
@ATayler The second example's return value is not aJust
, so I don't see how you can use it to support returning aJust
in some other case.
– Daniel Wagner
Mar 26 at 17:27
Same comment as I gave dfeuer: this does not appear to comply to the spec. Consider e.g.
gap 'a' 'b' "bacb"
-- this reports Just 2
, which is clearly incorrect. (Nothing
, Just 1
, or Just (-1)
all might be sensible choices depending on exactly how you interpret the spec.)– Daniel Wagner
Mar 26 at 11:46
Same comment as I gave dfeuer: this does not appear to comply to the spec. Consider e.g.
gap 'a' 'b' "bacb"
-- this reports Just 2
, which is clearly incorrect. (Nothing
, Just 1
, or Just (-1)
all might be sensible choices depending on exactly how you interpret the spec.)– Daniel Wagner
Mar 26 at 11:46
@DanielWagner thanks, see update
– Elmex80s
Mar 26 at 12:37
@DanielWagner thanks, see update
– Elmex80s
Mar 26 at 12:37
Ah nice, upvoted!
– Daniel Wagner
Mar 26 at 13:41
Ah nice, upvoted!
– Daniel Wagner
Mar 26 at 13:41
Just 2 seems correct to me @Daniel . The second example case indicates that the second argument should appear in the list at or beyond the first argument. On "bacb" then gap 'a' 'a' is Just 0, gap 'a' 'c' is Just 1, gap 'a' 'b' is Just 2
– moonGoose
Mar 26 at 16:40
Just 2 seems correct to me @Daniel . The second example case indicates that the second argument should appear in the list at or beyond the first argument. On "bacb" then gap 'a' 'a' is Just 0, gap 'a' 'c' is Just 1, gap 'a' 'b' is Just 2
– moonGoose
Mar 26 at 16:40
@ATayler The second example's return value is not a
Just
, so I don't see how you can use it to support returning a Just
in some other case.– Daniel Wagner
Mar 26 at 17:27
@ATayler The second example's return value is not a
Just
, so I don't see how you can use it to support returning a Just
in some other case.– Daniel Wagner
Mar 26 at 17:27
|
show 3 more comments
Here's how I'd do it:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x1 x2 xs = do
i <- elemIndex x1 xs
j <- elemIndex x2 xs
if i <= j
then Just (j - i)
else Nothing
Credits to dfeuer for reminding me of the elemIndex
function.
This is gratuitously inefficient.dropWhile
was the right way to start.
– dfeuer
Mar 26 at 5:24
1
@dfeuer I think it is about as efficient as can be done given the spec. If I have correctly guessed what you have in mind fordropWhile
, it will get the wrong answer forgap 'a' 'b' "bacb"
. (Whether the code in the answer gets it right or not is not clear -- the spec is a bit ambiguous, I have to say -- but thedropWhile
version will definitely get it wrong!)
– Daniel Wagner
Mar 26 at 5:27
@DanielWagner, it seems a bit ambiguous, but I see what you mean. However, it's still not the best way, because it traverses the list twice, retaining memory. You could use a slightly differentdropWhile
invocation, or to avoid a redundant test work up something custom.
– dfeuer
Mar 26 at 5:33
@dfeuer I agree. Without optimizations, this code is very inefficient. However, a smart compiler could most probably perform loop fusion to traverse the list only once. Either way, the first step is to get the program right, and the next step is to perform optimizations if necessary. If it doesn't matter that this code is inefficient, then let it be. However, if you find out that it's a performance bottleneck only then should you bother optimizing it.
– Aadit M Shah
Mar 26 at 11:08
add a comment |
Here's how I'd do it:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x1 x2 xs = do
i <- elemIndex x1 xs
j <- elemIndex x2 xs
if i <= j
then Just (j - i)
else Nothing
Credits to dfeuer for reminding me of the elemIndex
function.
This is gratuitously inefficient.dropWhile
was the right way to start.
– dfeuer
Mar 26 at 5:24
1
@dfeuer I think it is about as efficient as can be done given the spec. If I have correctly guessed what you have in mind fordropWhile
, it will get the wrong answer forgap 'a' 'b' "bacb"
. (Whether the code in the answer gets it right or not is not clear -- the spec is a bit ambiguous, I have to say -- but thedropWhile
version will definitely get it wrong!)
– Daniel Wagner
Mar 26 at 5:27
@DanielWagner, it seems a bit ambiguous, but I see what you mean. However, it's still not the best way, because it traverses the list twice, retaining memory. You could use a slightly differentdropWhile
invocation, or to avoid a redundant test work up something custom.
– dfeuer
Mar 26 at 5:33
@dfeuer I agree. Without optimizations, this code is very inefficient. However, a smart compiler could most probably perform loop fusion to traverse the list only once. Either way, the first step is to get the program right, and the next step is to perform optimizations if necessary. If it doesn't matter that this code is inefficient, then let it be. However, if you find out that it's a performance bottleneck only then should you bother optimizing it.
– Aadit M Shah
Mar 26 at 11:08
add a comment |
Here's how I'd do it:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x1 x2 xs = do
i <- elemIndex x1 xs
j <- elemIndex x2 xs
if i <= j
then Just (j - i)
else Nothing
Credits to dfeuer for reminding me of the elemIndex
function.
Here's how I'd do it:
import Data.List (elemIndex)
gap :: Eq a => a -> a -> [a] -> Maybe Int
gap x1 x2 xs = do
i <- elemIndex x1 xs
j <- elemIndex x2 xs
if i <= j
then Just (j - i)
else Nothing
Credits to dfeuer for reminding me of the elemIndex
function.
answered Mar 26 at 4:00
Aadit M ShahAadit M Shah
51.8k19 gold badges116 silver badges234 bronze badges
51.8k19 gold badges116 silver badges234 bronze badges
This is gratuitously inefficient.dropWhile
was the right way to start.
– dfeuer
Mar 26 at 5:24
1
@dfeuer I think it is about as efficient as can be done given the spec. If I have correctly guessed what you have in mind fordropWhile
, it will get the wrong answer forgap 'a' 'b' "bacb"
. (Whether the code in the answer gets it right or not is not clear -- the spec is a bit ambiguous, I have to say -- but thedropWhile
version will definitely get it wrong!)
– Daniel Wagner
Mar 26 at 5:27
@DanielWagner, it seems a bit ambiguous, but I see what you mean. However, it's still not the best way, because it traverses the list twice, retaining memory. You could use a slightly differentdropWhile
invocation, or to avoid a redundant test work up something custom.
– dfeuer
Mar 26 at 5:33
@dfeuer I agree. Without optimizations, this code is very inefficient. However, a smart compiler could most probably perform loop fusion to traverse the list only once. Either way, the first step is to get the program right, and the next step is to perform optimizations if necessary. If it doesn't matter that this code is inefficient, then let it be. However, if you find out that it's a performance bottleneck only then should you bother optimizing it.
– Aadit M Shah
Mar 26 at 11:08
add a comment |
This is gratuitously inefficient.dropWhile
was the right way to start.
– dfeuer
Mar 26 at 5:24
1
@dfeuer I think it is about as efficient as can be done given the spec. If I have correctly guessed what you have in mind fordropWhile
, it will get the wrong answer forgap 'a' 'b' "bacb"
. (Whether the code in the answer gets it right or not is not clear -- the spec is a bit ambiguous, I have to say -- but thedropWhile
version will definitely get it wrong!)
– Daniel Wagner
Mar 26 at 5:27
@DanielWagner, it seems a bit ambiguous, but I see what you mean. However, it's still not the best way, because it traverses the list twice, retaining memory. You could use a slightly differentdropWhile
invocation, or to avoid a redundant test work up something custom.
– dfeuer
Mar 26 at 5:33
@dfeuer I agree. Without optimizations, this code is very inefficient. However, a smart compiler could most probably perform loop fusion to traverse the list only once. Either way, the first step is to get the program right, and the next step is to perform optimizations if necessary. If it doesn't matter that this code is inefficient, then let it be. However, if you find out that it's a performance bottleneck only then should you bother optimizing it.
– Aadit M Shah
Mar 26 at 11:08
This is gratuitously inefficient.
dropWhile
was the right way to start.– dfeuer
Mar 26 at 5:24
This is gratuitously inefficient.
dropWhile
was the right way to start.– dfeuer
Mar 26 at 5:24
1
1
@dfeuer I think it is about as efficient as can be done given the spec. If I have correctly guessed what you have in mind for
dropWhile
, it will get the wrong answer for gap 'a' 'b' "bacb"
. (Whether the code in the answer gets it right or not is not clear -- the spec is a bit ambiguous, I have to say -- but the dropWhile
version will definitely get it wrong!)– Daniel Wagner
Mar 26 at 5:27
@dfeuer I think it is about as efficient as can be done given the spec. If I have correctly guessed what you have in mind for
dropWhile
, it will get the wrong answer for gap 'a' 'b' "bacb"
. (Whether the code in the answer gets it right or not is not clear -- the spec is a bit ambiguous, I have to say -- but the dropWhile
version will definitely get it wrong!)– Daniel Wagner
Mar 26 at 5:27
@DanielWagner, it seems a bit ambiguous, but I see what you mean. However, it's still not the best way, because it traverses the list twice, retaining memory. You could use a slightly different
dropWhile
invocation, or to avoid a redundant test work up something custom.– dfeuer
Mar 26 at 5:33
@DanielWagner, it seems a bit ambiguous, but I see what you mean. However, it's still not the best way, because it traverses the list twice, retaining memory. You could use a slightly different
dropWhile
invocation, or to avoid a redundant test work up something custom.– dfeuer
Mar 26 at 5:33
@dfeuer I agree. Without optimizations, this code is very inefficient. However, a smart compiler could most probably perform loop fusion to traverse the list only once. Either way, the first step is to get the program right, and the next step is to perform optimizations if necessary. If it doesn't matter that this code is inefficient, then let it be. However, if you find out that it's a performance bottleneck only then should you bother optimizing it.
– Aadit M Shah
Mar 26 at 11:08
@dfeuer I agree. Without optimizations, this code is very inefficient. However, a smart compiler could most probably perform loop fusion to traverse the list only once. Either way, the first step is to get the program right, and the next step is to perform optimizations if necessary. If it doesn't matter that this code is inefficient, then let it be. However, if you find out that it's a performance bottleneck only then should you bother optimizing it.
– Aadit M Shah
Mar 26 at 11:08
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55348906%2fhow-would-i-find-the-distance-between-two-elements-in-a-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
have a look at the
Data.List
library hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html , there are many different approaches to problems like this that depend on how much you want/have to write your own functions from scratch– Lorenzo
Mar 26 at 2:19
1
Also remember you can look for function by types on Hoogle hoogle.haskell.org, so in this case you would want a function that, given an element and a list, returns its index:
a -> [a] -> Maybe Int
– Lorenzo
Mar 26 at 2:21
2
What would
gap 'a' 'a' "a"
be?Just 0
orNothing
? How aboutgap 'a' 'a' "aa"
?Just 0
orJust 1
?– Joseph Sible
Mar 26 at 2:25
2
Possible duplicate of Gap function that returns the integer distance between first appearance of two elements in a list using either foldl or foldr.(Haskell)
– Joseph Sible
Mar 26 at 3:10
2
@AaditMShah, I would reach for
elemIndex
for the second part.– dfeuer
Mar 26 at 3:40