i have spent past afternoon or 2 poking @ computer if had never seen 1 before. today's topic lists
the exercise take string , capitalize every other letter. did not far...
let's take list x = string.tolist "abcde"
, try analyze it. if add results of take 1
, drop 1
original list
> x = string.tolist "abcde" ['a','b','c','d','e'] : list char > (list.take 1 x) ++ (list.drop 1 x) ['a','b','c','d','e'] : list char
i thought head
, tail
did same thing, big error message:
> [list.head x] ++ (list.tail x) ==================================== errors ==================================== -- type mismatch --------------------------------------------- repl-temp-000.elm right argument of (++) causing type mismatch. 7│ [list.head x] ++ (list.tail x) ^^^^^^^^^^^ (++) expecting right argument a: list (maybe char) right argument is: maybe (list char) hint: figure out type of left argument first , if acceptable on own, assume "correct" in subsequent checks. problem may in how left , right arguments interact.
the error message tells me lot of what's wrong. not 100% sure how fix it. list joining operator ++
expecting [maybe char]
, instead got maybe [char]
let's try capitalize first letter in string (which less cool, realistic).
[string.toupper ( list.head x)] ++ (list.drop 1 x)
this wrong since char.toupper
requires string
, instead list.head x
maybe char
.
[char.toupper ( list.head x)] ++ (list.drop 1 x)
this wrong since char.toupper
requires char
instead of maybe char
.
in real life user break script typing non-unicode character (like emoji). maybe elm's feedback right. should easy problem takes "abcde" , turns "abcde" (or possibly "abcde"). how handle errors properly?
- the same question in javascript: how make first letter of string uppercase in javascript?
in elm, list.head
, list.tail
both return maybe
type because either function passed invalid value; specifically, empty list. languages, haskell, throw error when passing empty list head
or tail
, elm tries eliminate many runtime errors possible.
because of this, must explicitly handle exceptional case of empty list if choose use head
or tail
.
note: there better ways achieve end goal of string mixed capitalization, i'll focus on head
, tail
issue because it's learning tool.
since you're using concatenation operator, ++
, you'll need list both arguments, it's safe create couple functions handle maybe
return values , translate them empty list, allow use concatenation operator.
myhead list = case list.head list of h -> [h] nothing -> [] mytail list = case list.tail list of t -> t nothing -> []
using case
statements above, can handle possible outcomes , map them usable circumstances. can swap myhead
, mytail
code , should set.
Comments
Post a Comment