I trying to compare a symbol to another alphabetically, but I can't do this.
In particular, I've done this.
CL-USER 1 > (string-lessp 'k 'a)
NIL
CL-USER 2 > (string-lessp 'a 'k)
0
Thank you guys
In Common Lisp, NIL is false, and anything else is true. So in your transcript, 0 is a true value, indicating that A is before K. Rather than simply returning T and NIL, STRING-LESSP returns a mismatch index:
The inequality functions return a mismatch-index that is true if the strings are not equal, or false otherwise. When the mismatch-index is true, it is an integer representing the first character position at which the two substrings differ, as an offset from the beginning of string1.
0 is the index of the first character where the designated strings don't agree.
Related
If I define an infinite list and call map over it with a function, I can take some number of elements from the beginning and Haskell will generate and apply the function only to these elements due to lazy evaluation
-- This will generate and process 10 elements
doubledNumbers = map (*2) [0..]
take 10 doubledNumbers
If I index this infinite mapping instead
doubledNumbers !! 9
will Haskell generate the list up to that point, apply the mapping function to all elements and give the element at index 9 back; or will it generate the list, apply the mapping function to the element at index 9, and give that back. In other words, which of the following (if any) would happen when I call doubledNumbers !! 9
The list [0,1,2,3,4,5,6,7,8,9] is generated, then the list [0,2,4,6,8,10,12,14,16,18], then 18 is taken from that list
The list [0,1,2,3,4,5,6,7,8,9] is generated, than 9 is taken from that list and given to (*2) , than (*2) returns 18
The second interpretation is the correct one (well, morally at least: see below for a better explanation):
The list [0,1,2,3,4,5,6,7,8,9] is generated, than 9 is taken from that list and given to (*2) , than (*2) returns 18
You can observe that the function ((*2) in your case) is not applied to other elements with the following experiment. First, define a function that will crash on every number except 9:
f 9 = 100 ; f _ = error "urk!"
Then try your code in GHCi, adapted to the new function
> doubledNumbers = map f [0..]
> doubledNumbers !! 9
100
If GHCi applied f to any other number you would observe the crash. This is a way to distinguish, through an experiment, lazy evaluation from eager evaluation.
More pedantically, entering in GHCi the code
> doubledNumbers = map (*2) [0..]
> doubledNumbers !! 9
will first generate a list similar to
(*2) 0 : (*2) 1 : .... : (*2) 9 : map (*2) [10..]
where the expressions are not yet evaluated. After that, GHCi will extract the 9th, causing it to be evaluated and printed.
Neither interpretation is correct. In fact, the list that's generated can be thought to look something like this:
[_,_,_,_,_,_,_,_,_,_...
In other words, the spine, or shape, of the list is forced up through the 9th element (and no further), but the actual values in the list aren't. Then, when you ask for the 9th element of the mapped list, GHC calls the function on that element without evaluating it unless necessary. You can observe this with the following experiment:
errorList = repeat (error "fail!")
trueList = map (const True) errorList
val = trueList !! 9
If the list were actually produced in the first place, then val would fail with fail! as soon as we try to print it. However, val properly is True.
Using the tracing facility:
It is often possible to answer this type of question using a little but handy tracing facility included in the Haskell runtime library.
So there is a trace function, such that evaluating the expression trace debugMsg expr will return the value of expr and, as a side effect, print the value of debugMsg to the standard error channel.
Yes, side effects are normally not available in Haskell, but the trace function enjoys a special privilege :-)
So you can replace your (*2) function with the equivalent one:
import qualified Debug.Trace as DT
doubler :: Int -> Int
doubler x = let debugMsg = "Doubling " ++ (show x) ++ " ... "
in DT.trace debugMsg (2*x)
And then you can test the various hypothesis under the ghci interpreter:
$ ghci
GHCi, version 8.8.4: https://www.haskell.org/ghc/ :? for help
λ>
λ> :load q65861408.hs
[1 of 1] Compiling Main ( q65861408.hs, interpreted )
Ok, one module loaded.
λ>
λ> :type doubler
doubler :: Int -> Int
λ>
λ> doubler 5
Doubling 5 ...
10
λ>
λ> doubledNumbers = map doubler [0..]
λ>
λ> doubledNumbers !! 9
Doubling 9 ...
18
λ>
And so it appears that, as mentioned in the other answers, the doubling function is only invoked for the input value 9.
This is because of the language laziness: the user did not ask to see the other doubled values, hence there is no need to compute them in the first place.
I have to write a function that has as parameters a dictionary and a character. The dictionary is string to string and you should look at it as a function. For example f("a")="b" in ("a", "b"). The function returns a max number for which f^number(character) is defined and an exception if f(character) cycles at infinity.
so if I have for eg this dictionary [("a", "b");("b", "c");("d", "e");("e", "f");("f", "e")]
my function appelead with this dictionary and charcater 'a' will give the result 2(a goes in b, b goes is c and it stops); for 'x' it will give 0 beacuse there's no such key; for 'b' the result will be 1(b goes in c and stops); for 'd' it will raise an exception(d goes in e, e goes in f, f goes in e and returns in e so infinite cycle); same exception for 'e' or 'f'
module MS = Map.Make(String);;
let d = MS.add "a" "b" (MS.add "b" "c" (MS.add "d" "e" (MS.add "e" "f" (MS.add "f" "e" MS.empty))));;
let f d c =
I just created the dictionary because I don't have any idea how could I implement this problem, but I think I need MS.Fold function for going through the dictionary.
The purpose of a fold is to "visit" all the elements of a structure, while accumulating some desired result. Your goal isn't to visit all the elements of your dictionary (which secretly is a graph). So a fold probably isn't what you want.
I'd say your main problem is in detecting cycles so you can raise an exception. To do this you need to track the places you've been. Then you raise the exception when you come to a place for the second time.
Otherwise this is a standard graph traversal problem, I'd say. You can solve it with a recursive function that visits nodes (i.e., looks up strings in the dictionary) until it gets a resolution. A resolution is a string that isn't in the dictionary, or a visit to a string that has already been visited.
Update
OK, I'll write some code that shows how to move through the dictionary. This function returns a string that is the concatenation of the first 10 strings it encounters. If it reaches a dead end before 10 it returns what it has seen so far. It uses your module MS.
let what_i_saw dict str =
let rec look sofar n s =
if n <= 0 then
sofar
else
match MS.find_opt s dict with
| None -> sofar
| Some s2 -> look (sofar ^ s2) (n - 1) s2
in
look str 9 str
Here's how it looks when you call the function:
# what_i_saw d "d";;
- : MS.key = "defefefefe"
# what_i_saw d "a";;
- : MS.key = "abc"
By the way, you say your function takes a character but your dictionary has keys that are strings. Strings and characters aren't the same thing in OCaml. I'm using strings everywhere in this example.
I am writing a recursive ML function, that takes a string, and an index value, and splits the string at the given index. The function should return a list containing two strings.
I understand that I need two base cases one to check if the index has been reached, and one to check if the string is out of characters. I am stuck on how I assign the characters to different strings. Note, I used a helper function to clean up the initial call, so that explode will not need to be typed on every function call.
fun spliatHelp(S, num) =
if null S then nil
else if num = 0 then hd(S) :: (*string2 and call with tl(S)*)
else hd(S) :: (*string1 and call with tl(S)*)
fun spliat(S, num) =
spliatHelp(explode(S), num);
From an input of spliat("theString", 3);
My ideal output would be ["the", "String"];
For the num = 0 case, you just need to return [nil, S] or (equivalently) nil :: S :: nil.
For the other case, you need to make the recursive call spliatHelp (tl S, num - 1) and then examine the result. You can use either a let expression or a case expression for that, as you prefer. The case expression version would look like this:
case spliatHelp (tl S, num - 1)
of nil => nil (* or however you want to handle this *)
| [first, second] => [hd S :: first, second]
| raise (Fail "unexpected result")
Incidentally, rather than returning a string list with either zero or two elements, I think it would be better and clearer to return a (string * string) option. (Or even just a string * string, raising an exception if the index is out of bounds.)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Searching through list
I need to write a function 'once' which, given a list of Integers and an Integer n, returns a Boolean indicating whether n occurs exactly once in the list. E.g.
Main> once [2,3,2,4] 2
False
Main> once [1..100] 2
True
And here is my current code:
once :: Int -> [Int] -> Bool
once x [] = False
once x (y:ys) = (x==y) || (once x ys)
It checks only whether x is part of the list, but it cannot tell x appeared more than once in the list and therefore return false.
Need help with this, thanks!
There are many possibilities doing that. If you know that the list is finite, you could say:
once x xs = length (filter (==x) xs) == 1
(If it's not finite, there is no solution.)
By the way, you had it almost in your solution, you just replace
|| (once x ys)
with
&& (x `notElem` ys)
Try this:
write a function once, that scans the list until it finds the element for the first time or the end of the list. In the latter case it returns False, else it calls once'on the rest of the list and returns the result.
once' does essentially the same as once, but returns False, if the element is found and True, if not.
Okay,
I've got the next definition of sequence:
datatype 'a seq = Nil | Cons of 'a * (unit-> 'a seq);
I need to implement the next function:
filterq_n:('a -> bool) -> int -> 'a seq -> 'a seq
The function gets a predicate function which returns true or false, n (integer) and sequence.
The functionality:
if n<=0 return the same seq.
else return a seq that its first n elements are the first n elements in the original seq that predicate returns true for them and the rest will be the same.
For example, if the predicate is (x mod 2) and the seq is 1,2,3,4,5... and n is 3 so the new seq is
2,4,6,7,8,...
In addition, I should check another 2 options:
2.1) if the seq is finite and has less than n elements that predicate returns true for them then the new seq will contain only the elements that predicate returns true for them.
2.2) if the seq is infinite and has less than n elements that predicate returns true for them then the new seq will contain all the elements that predicate returns true for them and when trying to get the next element it will enter to an infinite loop.
My current code logically was planned for now without considering 2.1 and 2.2 (although I get errors and can find why?)
fun filter_n (predicate: 'a -> bool ) (n: int) Nil = Nil
| filter_n (predicate: 'a -> bool ) (n: int) (Cons(x, xf)) =
if(n <= 0) then Cons(x, xf)
else
if predicate x then Cons(x, fn() => filter_n predicate n-1 (xf()) )
else filter_n predicate n-1 (xf())
;
syntax errors or drastic change..I am not sure?
(also, for 2.1 ans 2.2 I just need to check that if I got (Nil and n>0) then return Nil? )
Thanks in advance for any help.
You need to wrap n-1 in parens, otherwise it's interpreted as multiple arguments. After you did that, it will compile.
However there's still a logic error in your code: You're decreasing n whether the predicate matches or not. However the specification says that you should select n elements where the predicate matches, not that you should check the predicate for n elements. So you should only decrease n if the predicate matches and keep the same n otherwise.
Once you've fixed that, your code should meet the specification (including 2.1 and 2.2).